为什么在用list赋值时需要声明变量的类型?
在下面的代码中,我需要指定$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[]
#>发布于 2014-08-14 05:09:42
PowerShell函数将输出写入输出流,当将集合表示为输出时,默认行为是枚举该集合并输出它。当您将输出分配给集合时,您在另一边得到的是一个对象数组。也就是说,列表在输出操作期间丢失。您可以更改此行为,方法是将返回语句更改为:将列表包装在数组中,并将其作为单个元素;
return ,$list或者更简单地说是公正;
,$listhttps://stackoverflow.com/questions/25298190
复制相似问题