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

六月ゝ 毕业季﹏ 提交于 2020-01-06 17:01:00

问题


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?


回答1:


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.




回答2:


I found another workaround. Return a reference to the object:

[ref]$nvc

Only thing is, the caller has to dereference it before using it:

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

So definitely not as good as the unary , but still something interesting.



来源:https://stackoverflow.com/questions/32118702/why-cant-i-return-a-value-of-type-system-collections-specialized-namevaluecolle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!