我试图理解 Posh 中的数组展开,但以下内容让我感到困惑。在这个例子中,我返回包裹在另一个数组中的数组(使用逗号),这基本上在外部数组在返回时展开后给我原始数组。为什么当我通过对结果的变量使用数组运算符 (@) 间接包装结果时得到正确的结果(只是数组),但如果我直接在函数上使用 @ 则得到数组中的数组? @ operator 是否对其参数的不同类型表现不同? @运算符和数组展开有PS帮助文章吗?
function Unroll
{
return ,@(1,2,3)
}
Write-Host "No wrapper"
$noWrapper = Unroll #This is array[3]
$noWrapper | % { $_.GetType() }
Write-Host "`nWrapped separately"
$arrayWrapper = @($noWrapper) #No change, still array[3]
$arrayWrapper | % { $_.GetType() }
Write-Host "`nWrapped directly"
$directArrayWrapper = @(Unroll) #Why is this array[1][3] then?
$directArrayWrapper | % { $_.GetType() }
Write-Host "`nThe original array in elem 0"
$directArrayWrapper[0] | % { $_.GetType() }
谢谢
最佳答案
如果您从 Unroll
函数中删除逗号运算符,它的行为将如您所愿。
function Unroll
{
return @(1,2,3)
}
在这种情况下,$arrayWrapper = @($noWrapper)
与 $directArrayWrapper = @(Unroll)
相同。
您可以使用 this SO question 找到有关数组展开的更多信息在这个article about array literals In PowerShell
关于powershell - PowerShell 中的数组展开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11070014/