在列表之前放置逗号是如何影响其类型的?
请看以下代码:
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[]类型返回,而如果在getListMethodTwo中使用逗号,则它的类型为List[string]。
PS:我正在使用PSVersion 4.0
发布于 2014-08-13 06:55:42
当您返回集合时,PowerShell会为您解锁。一元逗号使用单个元素创建集合,因此“外部”集合将被解压并保留您想要返回的集合。
我很久以前就说过了。
还有两件事:
return在PowerShell中用于尽早离开函数,不需要从函数返回某些内容(任何未捕获的输出都会返回)Write-Output -NoEnumerate $collection来防止解压您的集合。发布于 2014-08-13 06:56:26
我没有一个完整的答案,但我敢打赌这与PowerShell的“扁平化”行为有关。
通过使用一元运算符“,”您将围绕$list对象创建一个新的集合包装器。在PowerShell‘扁平化’之后,您将看到包装器中的对象。
https://stackoverflow.com/questions/25279112
复制相似问题