使用逗号而不是使用逗号返回List [String]

Bac*_*ave 4 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
Run Code Online (Sandbox Code Playgroud)

为什么呢,如果你不返回之前使用逗号$listgetListMethodOne它返回类型System.Object[],而如果你在做使用逗号getListMethodTwo,它的类型List[string]如预期?

PS:我正在使用PSVersion 4.0

Bar*_*ekB 7

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

我刚才在博客上发表这篇文章.

还有两件事:

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