今天,我注意到PowerShell的一种令人感兴趣的行为,并编写了以下代码来演示它。运行时:
function test()
{
$a = @(1,2);
Write-Host $a.gettype()
return $a;
}
$b = test
Write-Host $b.gettype();
你得到的是:
System.Object[]
System.Object[]
但是,当您将代码更改为:
function test()
{
$a = @(1);
Write-Host $a.gettype()
return $a;
}
$b = test
Write-Host $b.gettype();
您将获得:
System.Object[]
System.Int32
有人可以提供有关此“功能”的更多详细信息吗?似乎PowerShell规范没有提及这一点。
谢谢。
顺便说一句,我在PowerShell版本2、3和4上测试了代码。
最佳答案
在某些情况下,Powershell会自动“解包”阵列,在您的情况下,分配是:
PS> (test).GetType()
System.Object[]
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Int32 System.ValueType
PS> $b = test
System.Object[]
PS> $b.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Int32 System.ValueType
您可以通过在分配中显式引入一个数组来解决这个问题:
$b = ,(test)
关于arrays - PowerShell从函数返回单个元素数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20993403/