为什么我不能返回System.Collections.Specialized.NameValueCollection类型的值? [英] Why can't I return a value of type System.Collections.Specialized.NameValueCollection?
问题描述
我可以创建 [System.Collections.Specialized.NameValueCollection]
类型的新实例,并且它似乎正常工作。但是如果我在一个函数中执行它,然后返回该对象,则调用者会收到一个 [String]
(如果集合只包含单个项目)或 [Object []]
,如果它包含多个项目(然后该数组中的每个项目是 [String]
键)。
这可以用下面的代码复制:
函数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 =测试返回类型
写入详细$ r.GetType()-Verbose
我已经确认 .Add()
方法有一个 [void]
返回类型,并且管道到 Out-Null
不会更改行为。
我尝试添加一个 [OutputType()]
属性给函数,即使我知道这只是为了文档。
我在函数的最后一行尝试铸造 $ nvc
效果)。
我试着铸造 $ r
和 Test的返回值-ReturnType
(例外,无法转换)。
我只是不明白为什么这是不可能的。
例如,如果我创建一个新的 [System.Net.WebClient]
并从函数返回它,它就可以工作。
为什么 [System.Collections.Specialized.NameValueCollection]
会在返回时变成存储值?
Powershell在这里有帮助,并以解开数组/等等的方式解开你的集合。因为它们进入管道。
您需要通过为PowerShell添加一个数组/包装层来解除。
尝试,$ nvc
作为最后一行。 这个问题关于Powerhell展开的一些讨论。
I can create a new instance of the [System.Collections.Specialized.NameValueCollection]
type, and it seems to work fine. But if I do it inside a function, and then return the object, the caller receives either a [String]
(if the collection contains only a single item) or [Object[]]
if it contains multiple items (and then each item in that array is a [String]
representing one of the keys).
This can be reproduced with the following code:
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
I've confirmed that the .Add()
method has a [void]
return type, and piping to Out-Null
doesn't change the behavior.
I've tried to add an [OutputType()]
attribute to the function even though I know that's for documentation only.
I've tried casting $nvc
in the last line of the function (no effect).
I've tried casting $r
and the return value of Test-ReturnType
(exception, can't convert).
I just don't understand why this isn't possible.
If I create a new [System.Net.WebClient]
for example and return that from the function, it works just fine.
Why does [System.Collections.Specialized.NameValueCollection]
get turned into its stored values upon return?
Powershell is being "helpful" here and unwrapping your collection for you the same way it unwraps arrays/etc. as they enter the pipeline.
You need to "prevent" that by adding a layer of array/wrapping for powershell to unwrap instead.
Try ,$nvc
as the last line instead.
See this question for some discussion about powershell unrolling.
这篇关于为什么我不能返回System.Collections.Specialized.NameValueCollection类型的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!