[System.Collections.Generic.List[string]]作为返回值
我需要/想要[System.Collections.Generic.List[string]]从函数返回 a ,但它被包含在一个System.Object[]
我有这个
function TestReturn {
$returnList = New-Object System.Collections.Generic.List[string]
$returnList.Add('Testing, one, two')
return ,@($returnList)
}
$testList = TestReturn
$testList.GetType().FullName
它将它作为 a 返回System.Object[],如果我将返回行更改为
return [System.Collections.Generic.List[string]]$returnList
或者
return [System.Collections.Generic.List[string]]@($returnList)
在这两种情况下,当[System.String]列表中有一项时,它返回 a ,System.Object[]如果有多个项,则返回 a 。列表有什么奇怪的地方不能用作返回值吗?
现在,奇怪的是(我认为)如果我像这样键入接收值的变量,它确实有效。
[System.Collections.Generic.List[string]]$testList = TestReturn
但这似乎是某种奇怪的强制转换,其他数据类型不会发生这种情况。
回答
如果删除数组子表达式@(...)并在前面加上逗号。下面的代码似乎工作:
function TestReturn {
$returnList = New-Object System.Collections.Generic.List[string]
$returnList.Add('Testing, one, two')
return , $returnList
}
$testList = TestReturn
$testList.GetType().FullName
注意:从技术上讲,这会导致返回[Object[]]一个类型为 的元素[System.Collections.Generic.List[string]]。但同样由于隐式展开,它会诱使 PowerShell 根据需要进行输入。
稍后,语法[Type]$Var类型会限制变量。它基本上锁定了该变量的类型。因此,后续调用.GetType()将返回该类型。
这些问题是由于 PowerShell 如何在输出上隐式展开数组。典型的解决方案(在某种程度上取决于类型)是在返回之前使用 a,或确保调用端的数组,或者通过类型约束您的问题中所示的变量,或者包装或转换返回本身。后者可能类似于:
$testList = [System.Collections.Generic.List[string]]TestReturn
$testList.GetType().FullName
为了在标量返回可能时确保数组并假设您没有在 return 语句之前使用,,您可以在调用端使用数组子表达式:
$testList = @( TestReturn )
$testList.GetType().FullName
我相信这个答案涉及类似的问题
THE END
二维码