2008-10-08 41 views
35

我一直在推入PowerShell中的.NET框架,并且碰到了一些我不明白的东西。这工作得很好:PowerShell通用集合

$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的一个问题。

回答

17

词典< K,V>没有在与SortedDictionary < K,V>相同的程序集中定义。一个在mscorlib中,另一个在system.dll中。

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

在这种情况下,这意味着它在System.dll中寻找System.String,而不是在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]]" 
+0

有没有任何描述这种语法的参考?我试图从Powershell对象实现BeginInvoke,并在其中的一个重载中使用输入和输出参数。我似乎无法得到正确的声明。 – 2012-06-13 18:05:57

4

在PowerShell中泛型存在一些问题。 Lee Holmes,PowerShell团队的开发人员发布了this script来创建泛型。

+2

[缓存链接](https://web.archive.org/web/20090926122811 /http://www.leeholmes.com/blog/CreatingGenericTypesInPowerShell.aspx) – user2426679 2016-02-02 22:30:52

+1

这是“今晚”吗? :) – mklement0 2016-10-24 22:04:23

78

在PowerShell 2.0中新的方法来建立一个Dictionary是:

$object = New-Object 'system.collections.generic.dictionary[string,int]'