【发布时间】:2021-05-20 19:31:45
【问题描述】:
我需要/想要从函数返回 [System.Collections.Generic.List[string]],但它被覆盖到 System.Object[]
我有这个
function TestReturn {
$returnList = New-Object System.Collections.Generic.List[string]
$returnList.Add('Testing, one, two')
return ,@($returnList)
}
$testList = TestReturn
$testList.GetType().FullName
将其作为System.Object[] 返回,如果我将返回行更改为
return [System.Collections.Generic.List[string]]$returnList
或
return [System.Collections.Generic.List[string]]@($returnList)
如果列表中有一项,则返回[System.String],如果有多个项,则返回System.Object[],在这两种情况下。列表有什么奇怪的地方不能用作返回值吗?
现在,奇怪的是(我认为)如果我像这样键入接收值的变量,它确实可以工作。
[System.Collections.Generic.List[string]]$testList = TestReturn
但这似乎是一种奇怪的强制转换,其他数据类型不会发生这种情况。
【问题讨论】:
-
我猜默认情况下,PowerShell 会假定
System.Array,但如果你这样做[collections.generic.list[string]]$testList = TestReturn,即使函数返回一个字符串,它也应该可以正常工作。
标签: powershell return-type generic-list