为什么我不能 return 类型 System.Collections.Specialized.NameValueCollection 的值?

Why can't I return a value of type System.Collections.Specialized.NameValueCollection?

我可以创建一个 [System.Collections.Specialized.NameValueCollection] 类型的新实例,它似乎工作正常。但是,如果我在函数内部执行此操作,然后 return 对象,则调用者会收到 [String] (如果集合仅包含一个项目)或 [Object[]] 如果它包含多个项目(然后该数组中的每个项目都是 [String] 代表其中一个键)。

可以使用以下代码重现:

function Test-ReturnType {
[CmdletBinding()]
param()

    $nvc = New-Object System.Collections.Specialized.NameValueCollection
    Write-Verbose $nvc.GetType() -Verbose
    $nvc.Add('Name1','Value1')
    $nvc.Add('Name2','Value2')
    $nvc
}

$r = Test-ReturnType

Write-Verbose $r.GetType() -Verbose

我已经确认 .Add() 方法有一个 [void] return 类型,并且管道到 Out-Null 不会改变行为。

我尝试向该函数添加 [OutputType()] 属性,尽管我知道这仅用于文档。

我试过在函数的最后一行强制转换 $nvc(无效)。

我试过转换 $rTest-ReturnType 的 return 值(异常,无法转换)。

我只是不明白为什么这是不可能的。

例如,如果我创建一个新的 [System.Net.WebClient] 并从该函数创建 return,它就可以正常工作。

为什么 [System.Collections.Specialized.NameValueCollection] 在 return 时变成了它的存储值?

Powershell 正在 "helpful" 此处,并以与解包 arrays/etc 相同的方式为您解包 collection。当他们进入管道时。

您需要 "prevent" 通过为 powershell 添加一层 array/wrapping 来解包。

尝试将 ,$nvc 作为最后一行。

有关 powershell 展开的一些讨论,请参阅 this question

我找到了另一个解决方法。 Return 对对象的引用:

[ref]$nvc

唯一的问题是,调用者必须在使用它之前取消引用它:

$r = Test-ReturnType
$r.value.GetType()

所以肯定不如一元 , 但仍然很有趣。