Powershell 使用逗号返回列表[字符串]与不使用逗号返回列表[字符串]
在列表前加逗号如何影响其类型 请查看以下代码:Powershell 使用逗号返回列表[字符串]与不使用逗号返回列表[字符串],powershell,Powershell,在列表前加逗号如何影响其类型 请查看以下代码: function StartProgram { $firstList = getListMethodOne Write-Host "firstList is of type $($firstList.gettype())" $secondList = getListMethodTwo Write-Host "secondList is of type $($secondList.gettype())" } fun
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
为什么,如果在getListMethodOne
中返回$list
之前不使用逗号,则返回的类型为System.Object[]
,而如果在getListMethodTwo
中使用逗号,则返回的类型为list[string]
PS:当您返回集合时,我使用的是PSVersion4.0,PowerShell很乐意为您解开它。 一元逗号使用单个元素创建集合,所以“外部”集合将被分解,并且要返回的集合将被保留 我不久前就知道了 还有两件事:
在PowerShell中用于提前离开函数,不需要从函数返回某些内容(返回任何未捕获的输出)return
- 在PowerShell 4.0中,您可以使用
来防止拆分您的集合Write Output-NoEnumerate$collection
- 我没有完整的答案,但我敢打赌这与PowerShell的“扁平化”行为有关
通过使用一元运算符“,”可以围绕$list对象创建一个新的集合包装器。在PowerShell将其“展平”后,您将看到包装器中的对象
这里有一个更完整的解释:为什么在getListMethodOne中,当我将其声明为List[String]时,类型返回为System.Object[]?一旦解开
List[String]
,它的每个元素都会沿着管道发送。我们有多个,因此PowerShell将结果存储为System.Object[]。您在函数范围内声明了变量的类型。若类型遵循“让我们为管道做得更好”,那个么这对函数结果并没有影响。如果是这种情况,则需要使用一元逗号“保护”集合,或者告诉PowerShell使用-NoEnumerate
写入输出。