问题
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