PowerShell 通用集合
我一直在 PowerShell 中推进 .NET 框架,但遇到了一些我不明白的问题。 这工作正常:
$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]"
它们都在同一个程序集中,那么我错过了什么?
正如答案中所指出的,这几乎只是 PowerShell v1 的问题。
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
This however does not:
$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?
As was pointed out in the answers, this is pretty much only an issue with PowerShell v1.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 PowerShell 2.0 中创建
Dictionary
的新方法是:In PowerShell 2.0 the new way to create a
Dictionary
is:字典未在与 SortedDictionary相同的程序集中定义。 一个在 mscorlib 中,另一个在 system.dll 中。
问题就在于此。 PowerShell 中的当前行为是,在解析指定的泛型参数时,如果类型不是完全限定的类型名称,它会假定它们与您尝试实例化的泛型类型位于同一程序集中。
在这种情况下,这意味着它正在 System.dll 中查找 System.String,而不是在 mscorlib 中,因此失败。
解决方案是为通用参数类型指定完全限定的程序集名称。 它非常丑陋,但有效:
Dictionary<K,V> is not defined in the same assembly as SortedDictionary<K,V>. One is in mscorlib and the other in system.dll.
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.
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:
PowerShell 中的泛型存在一些问题。 PowerShell 团队的开发人员 Lee Holmes 发布了此脚本来创建泛型。
There are some issues with Generics in PowerShell. Lee Holmes, a dev on the PowerShell team posted this script to create Generics.