【问题标题】:PowerShell generic collectionsPowerShell 泛型集合
【发布时间】:2008-10-08 19:34:15
【问题描述】:

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

【问题讨论】:

    标签: .net powershell powershell-1.0


    【解决方案1】:

    在 PowerShell 2.0 中,创建 Dictionary 的新方法是:

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

    【讨论】:

    • 确实,这是一个更好的答案。 如果用户使用的是 v2。不过,这个问题是关于 v1 的。世界上仍然有很多人也在使用 v1。
    • 显然,如果在第 3 方程序集中声明了其中一种类型:stackoverflow.com/questions/11975130,您将在 v2 中遇到同样的问题。这似乎已在 v4 中修复
    【解决方案2】:

    Dictionary 未在与 SortedDictionary 相同的程序集中定义。一个在 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]]"
    

    【讨论】:

    • 有没有描述这种语法的参考资料?我正在尝试从 Powershell 对象实现 BeginInvoke,并且在其中一个重载中使用输入和输出参数有一段时间。我似乎无法正确声明。
    【解决方案3】:

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-05
    • 1970-01-01
    • 1970-01-01
    • 2013-11-19
    • 1970-01-01
    • 2012-09-16
    • 1970-01-01
    相关资源
    最近更新 更多