Powershell需要指定对象的类型
为什么在使用列表分配变量时需要声明变量的类型 在下面的代码中,我需要指定Powershell需要指定对象的类型,powershell,Powershell,为什么在使用列表分配变量时需要声明变量的类型 在下面的代码中,我需要指定$firstList的类型为list[string],如果我不这样做,那么它的类型为Object[],即使在返回该列表的函数中,列表的类型为list[string] function StartProgram { [system.collections.generic.list[string]]$firstList = getList $secondList = getList Write-Host
$firstList
的类型为list[string]
,如果我不这样做,那么它的类型为Object[]
,即使在返回该列表的函数中,列表的类型为list[string]
function StartProgram
{
[system.collections.generic.list[string]]$firstList = getList
$secondList = getList
Write-Host "firstList is of type $($firstList.gettype())"
Write-Host "secondList is of type $($secondList.gettype())"
}
function getList
{
$list = new-object system.collections.generic.list[string]
$list.Add("foo")
$list.Add("bar")
return $list
}
StartProgram
<#
Output:
firstList is of type System.Collections.Generic.List[string]
secondList is of type System.Object[]
#>
功能启动程序
{
[system.collections.generic.list[string]$firstList=getList
$secondList=getList
写入主机“firstList的类型为$($firstList.gettype())”
写入主机“secondList的类型为$($secondList.gettype())”
}
函数getList
{
$list=新对象system.collections.generic.list[string]
$list.Add(“foo”)
$list.Add(“bar”)
返回$list
}
启动程序
PowerShell函数将输出写入输出流,当集合显示为输出时,默认行为是枚举该集合和输出。另一方面,当您将输出分配给集合时,得到的是对象数组。也就是说,列表在输出操作期间丢失。您可以通过将return语句改为,将列表包装在数组中,并将其作为单个元素来更改此行为
return ,$list
或者更简单地说,只是
,$list
是return关键字把你扔了出去。看看[这个]()。如果在返回之前检查
$list
的类型,您会发现它是正确的对象类型。我去掉了return关键字,但它没有改变任何内容。是否可以在函数上指定一个属性来防止这种“自动枚举”功能并简单地按原样返回对象?否,但V5中可能会有一个功能允许您在类中创建方法。希望那些def
方法不会枚举输出,但现在确定还为时过早(或者即使该功能将其转换为最终位)。