为什么我可以在空数组上调用GetType(),而不是从函数返回时调用

jam*_*iet 5 powershell

在我不断追求更好地理解Powershell的过程中,有人可以向我解释这种行为:

function fn1{return @()}
(@()).GetType()           #does not throw an error
(fn1).GetType()           #throws error "You cannot call a method on a null-valued expression."
Run Code Online (Sandbox Code Playgroud)

为什么从函数返回一个值使它"不同"?

有趣的是(或许不是),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."
Run Code Online (Sandbox Code Playgroud)

让我困惑的颜色.有人可以解释一下吗?

Ada*_*ski 4

发生这种情况是因为当您从函数返回数组(可能还有任何其他集合)时,PowerShell 会将数组的每个元素放入管道中。所以GetType()实际上不是在空数组上调用,而是它的元素(丢失)。

解决方案可能是将您的数组返回到另一个数组中:)。

function fn1{return ,@()}
(fn1).GetType() 
Run Code Online (Sandbox Code Playgroud)

现在,Powershell 将将此“父”数组的元素传递到管道中,该数组恰好只包含一个元素:空数组。请注意,您无法通过 实现这一点return @(@()),因为 external@()只能确保返回的结果将是一个数组,而它已经是一个数组。