如何在列表前面添加逗号会影响其类型?
查看以下代码:
function StartProgram
{
$firstList = getListMethodOne
Write-Host "firstList is of type $($firstList.gettype())"
$secondList = getListMethodTwo
Write-Host "secondList is of type $($secondList.gettype())"
}
function getListMethodOne
{
$list = new-object system.collections.generic.list[string]
$list.Add("foo") #If there is one element, $list is of type String
$list.Add("bar") #If there is more than one element, $list is of type System.Object[]
return $list
}
function getListMethodTwo
{
$list = new-object system.collections.generic.list[string]
$list.Add("foo")
$list.Add("bar")
return ,$list #This is always of type List[string]
}
StartProgram
为什么,如果你在$list
中返回getListMethodOne
之前没有使用逗号,则返回类型为System.Object[]
,而如果你在{{1}中使用逗号它是预期的类型getListMethodTwo
?
PS:我正在使用PSVersion 4.0
答案 0 :(得分:7)
当您返回集合时,PowerShell非常友好地为您解开它。 一元逗号使用单个元素创建集合,因此“外部”集合将被解开并保留您想要返回的集合。
我blogged前一段时间。
还有两件事:
return
提前保留函数,不需要从函数返回任何内容(返回任何未捕获的输出)Write-Output -NoEnumerate $collection
来防止破坏您的收藏。答案 1 :(得分:0)
我没有完整的答案,但我敢打赌这与PowerShell的“扁平化”行为有关。
通过使用一元运算符','您将在$ list对象周围创建一个新的集合包装器。在PowerShell'展平'之后,您会看到包装内的对象。