在我不断追求更好地了解Powershell的追求中,有人可以向我解释这种行为:
function fn1{return @()}
(@()).GetType() #does not throw an error
(fn1).GetType() #throws error "You cannot call a method on a null-valued expression."
为什么从函数返回值会使它“不同”?
有趣的是(或者可能不是),在两种情况下用管道传递到get-member表现出相同的行为:
function fn1{return @()}
@() | gm #does throw an error "You cannot call a method on a null-valued expression."
fn1 | gm #does throw an error "You cannot call a method on a null-valued expression."
使我困惑。有人可以解释吗?
发生这种情况的原因是,当您从函数返回数组(可能还有其他集合)时,PowerShell会将数组的每个元素放入管道中。因此GetType()
实际上并不是在空数组上调用它,而是元素(丢失了)。
解决方法可能是将您的数组返回另一个数组:)。
function fn1{return ,@()}
(fn1).GetType()
现在,Powershell将传递到此“父”数组的管道元素中,该元素仅包含一个元素:空数组。请注意,您无法通过实现此目标return @(@())
,因为@()
仅外部确保返回的结果将是一个数组,该数组已经存在。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句