PowerShell通用集合

37

我一直在使用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的问题。

3个回答

83
在PowerShell 2.0中创建一个Dictionary新的方法是:
$object = New-Object 'system.collections.generic.dictionary[string,int]'

7
如果用户使用的是v2,那么这确实是一个更好的回答。不过该问题是针对v1提出的。全球仍有大量用户在使用v1。 - EBGreen
显然,如果其中一个类型在第三方程序集中声明,您在v2中将遇到相同的问题:https://dev59.com/FWct5IYBdhLWcg3wmOdO。这似乎在v4中已修复。 - marsze

20

Dictionary<K,V>未在与SortedDictionary<K,V>相同的程序集中定义。其中一个在mscorlib中,另一个在system.dll中。

问题就在这里。在PowerShell中,解析指定的泛型参数时,如果类型不是完全限定的类型名称,它会假设它们与您尝试实例化的泛型类型在同一个程序集中。

在这种情况下,它意味着它正在查找System.String在System.dll中,而不是在mscorlib中,因此失败了。

解决方案是为泛型参数类型指定完全限定的程序集名称。这非常丑陋,但很有效:

$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]]"

1
有没有任何参考资料描述这个语法?我正在尝试从Powershell对象实现BeginInvoke,但在其中一个重载中使用输入和输出参数非常困难。我似乎无法正确声明它。 - Tom H

4

PowerShell中的泛型存在一些问题。PowerShell团队的开发人员Lee Holmes发布了这个脚本来创建泛型。


3
缓存链接 - sam-6174
1
现在是“今晚”了吗? :) - mklement0
创建 PowerShell 中的通用类型 - Ben Thul

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接