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 のみの問題です。

4

3 に答える 3

83

PowerShell 2.0 では、新しい作成方法Dictionaryは次のとおりです。

$object = New-Object 'system.collections.generic.dictionary[string,int]'
于 2010-02-04T19:23:31.057 に答える
20

Dictionary<K,V> は、SortedDictionary<K,V> と同じアセンブリで定義されていません。1 つは mscorlib にあり、もう 1 つは system.dll にあります。

そこに問題があります。PowerShell の現在の動作では、指定されたジェネリック パラメーターを解決するときに、型が完全修飾型名でない場合、インスタンス化しようとしているジェネリック型と同じアセンブリにあると想定されます。

この場合、mscorlib ではなく System.dll で System.String を探していることを意味するため、失敗します。

解決策は、ジェネリック パラメーター型の完全修飾アセンブリ名を指定することです。それは非常に醜いですが、動作します:

$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]]"
于 2008-10-09T03:54:42.190 に答える
4

PowerShell の Generics にはいくつかの問題があります。PowerShell チームの開発者である Lee Holmes は、ジェネリックを作成するためにこのスクリプトを投稿しました。

于 2008-10-08T22:30:19.487 に答える