使用逗号返回List [String]或不使用逗号

时间:2014-08-13 06:05:40

标签: powershell

如何在列表前面添加逗号会影响其类型?

查看以下代码:

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

2 个答案:

答案 0 :(得分:7)

当您返回集合时,PowerShell非常友好地为您解开它。 一元逗号使用单个元素创建集合,因此“外部”集合将被解开并保留您想要返回的集合。

blogged前一段时间。

还有两件事:

    PowerShell中使用
  • return提前保留函数,不需要从函数返回任何内容(返回任何未捕获的输出)
  • 在PowerShell 4.0中,您可以使用Write-Output -NoEnumerate $collection来防止破坏您的收藏。

答案 1 :(得分:0)

我没有完整的答案,但我敢打赌这与PowerShell的“扁平化”行为有关。

通过使用一元运算符','您将在$ list对象周围创建一个新的集合包装器。在PowerShell'展平'之后,您会看到包装内的对象。

这里有更全面的解释:http://rkeithhill.wordpress.com/2007/09/24/effective-powershell-item-8-output-cardinality-scalars-collections-and-empty-sets-oh-my/