PowerShell的泛型集合PowerShell

2023-09-02 01:52:38 作者:凉生荒城°

我一直推到在PowerShell中的.NET Framework和我都碰到了什么东西,我不明白。这工作得很好:

I have been pushing into the .Net framework in powershell and I have hit something that I don't understand. This works fine:

13# $foo = New-Object "System.Collections.Generic.Dictionary``2[System.String,System.String]"
14# $foo.Add("FOO", "BAR")
15# $foo

Key                                                         Value
---                                                         -----
FOO                                                         BAR

然而,这并不:

This however does not:

16# $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 pretty的多只问题

As was pointed out in the answers, this is pretty much only an issue with powershell v1.

推荐答案

字典是不是在同一个组件,SortedDictionary定义。一个是在mscorlib中,另一个在system.dll中。

Dictionary is not defined in the same assembly as SortedDictionary. 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.String在System.dll中,而不是在mscorlib程序,所以它失败

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