PowerShell 通用集合 [英] PowerShell generic collections
问题描述
我一直在 PowerShell 中推进 .NET 框架,但遇到了一些我不明白的问题.这工作正常:
I have been pushing into the .NET framework in PowerShell, and I have hit something that I don't understand. This works fine:
$foo = New-Object "System.Collections.Generic.Dictionary``2[System.String,System.String]"
$foo.Add("FOO", "BAR")
$foo
Key Value
--- -----
FOO BAR
然而这不会:
$bar = New-Object "System.Collections.Generic.SortedDictionary``2[System.String,System.String]"
New-Object : Cannot find type [System.Collections.Generic.SortedDictionary`2[System.String,System.String]]: make sure t
he assembly containing this type is loaded.
At line:1 char:18
+ $bar = New-Object <<<< "System.Collections.Generic.SortedDictionary``2[System.String,System.String]"
它们都在同一个程序集中,所以我错过了什么?
They are both in the same assembly, so what am I missing?
正如答案中所指出的,这几乎只是 PowerShell v1 的一个问题.
As was pointed out in the answers, this is pretty much only an issue with PowerShell v1.
推荐答案
Dictionary
Dictionary<K,V> is not defined in the same assembly as SortedDictionary<K,V>. One is in mscorlib and the other in system.dll.
问题就在这里.PowerShell 中的当前行为是,在解析指定的泛型参数时,如果类型不是完全限定的类型名称,它会假设它们与您尝试实例化的泛型类型在同一个程序集中.
Therein lies the problem. The current behavior in PowerShell is that when resolving the generic parameters specified, if the types are not fully qualified type names, it sort of assumes that they are in the same assembly as the generic type you're trying to instantiate.
在这种情况下,这意味着它正在 System.dll 中而不是在 mscorlib 中查找 System.String,因此它失败了.
In this case, it means it's looking for System.String in System.dll, and not in mscorlib, so it fails.
解决方案是为泛型参数类型指定完全限定的程序集名称.它非常丑陋,但有效:
The solution is to specify the fully qualified assembly name for the generic parameter types. It's extremely ugly, but works:
$bar = new-object "System.Collections.Generic.Dictionary``2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"
这篇关于PowerShell 通用集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!