首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用逗号返回List[String]与不使用逗号

问使用逗号返回List[String]与不使用逗号
EN

Stack Overflow用户
提问于 2014-08-13 06:05:40
回答 2查看 2.8K关注 0票数 7

在列表之前放置逗号是如何影响其类型的?

请看以下代码:

代码语言:javascript
复制
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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-08-13 06:55:42

当您返回集合时,PowerShell会为您解锁。一元逗号使用单个元素创建集合,因此“外部”集合将被解压并保留您想要返回的集合。

我很久以前就说过了。

还有两件事:

  • return在PowerShell中用于尽早离开函数,不需要从函数返回某些内容(任何未捕获的输出都会返回)
  • 在PowerShell 4.0中,您可以使用Write-Output -NoEnumerate $collection来防止解压您的集合。
票数 11
EN

Stack Overflow用户

发布于 2014-08-13 06:56:26

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

通过使用一元运算符“,”您将围绕$list对象创建一个新的集合包装器。在PowerShell‘扁平化’之后,您将看到包装器中的对象。

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25279112

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档