13

Powershelのジェネリックはかなり混乱しています。簡単なリストをインスタンス化するには、タンバリンを持って踊る必要があります。

$type = ("System.Collections.Generic.List"+'`'+"1") -as "Type"
$type= $type.MakeGenericType("System.string" -as "Type")
$o = [Activator]::CreateInstance($type)

<Dictionary<string,List<Foo>>しかし、たとえば、もう少し複雑なものが必要な場合はどうなりますか?

または例えばここに:Dictionary<string,List<string>>

$listType = ("System.Collections.Generic.List"+'`'+"1") -as "Type"
$listType = $listType.MakeGenericType("System.string" -as "Type")
$L = [Activator]::CreateInstance($listType)

$dicType = ("System.Collections.Generic.Dictionary"+'`'+"2") -as "Type"

#the next line is problematic
$dicType = $dicType.MakeGenericType( 
     @( ("system.string" -as "Type"), 
        ("System.Collections.Generic.List" as "Type)) # and that's of course wrong
      )

$D = [Activator]::CreateInstance($dicType )
4

4 に答える 4

26

CLR の内部表現を掘り下げて自分の人生を困難にすることはできますが、次のことを行う必要はありませ

$dict = new-object 'collections.generic.dictionary[string,int]'
$dict.add("answer", 42)

型リテラル表現が必要ですか?

[collections.generic.dictonary[string,int]]

終わり。ジェネリック型パラメーターはどうですか?

$dictOfList = new-object 'collections.generic.dictionary[string,
    [collections.generic.list[int]]]'

終わり。

ただし、残念な落とし穴があります。PowerShell 2.0 では、BCL とサード パーティの型を型パラメーターとして混在させるとバグが発生します。後者はアセンブリ修飾する必要があります。

# broken over two lines for clarity with backtick escape
$o = new-object ('collections.generic.dictionary[[{0}],[{1}]]' -f `
        [type1].fullname, [type2].fullname)

お役に立てれば。PowerShell 3.0 では、これが修正されました。

于 2012-08-15T20:53:00.770 に答える
0

カスタム型が定義されたディクショナリを作成している場合、上記の例はそれほど複雑である必要はありません。

$propertiesType = ("System.Collections.Generic.Dictionary"+'`'+"2") -as "Type"
$propertiesType = $propertiesType.MakeGenericType( @( ("System.string" -as "Type"), ("Namespace.CustomType" -as "Type")))
$properties = [Activator]::CreateInstance($propertiesType)
于 2013-07-25T20:44:08.890 に答える
0

ええ、それは可能だと思われますが、PS の他のほとんどすべてと同様に、これも醜いです。実際の例を次に示します。

$requestItemsTypeですDictionary<string, List<Amazon.DynamoDB.Model.WriteRequest>>

$wrt = ("System.Collections.Generic.List``1" -as "Type") 
$wrt = $wrt.MakeGenericType( @( ("Amazon.DynamoDB.Model.WriteRequest" -as "Type")))

$requestItemsType = ("System.Collections.Generic.Dictionary"+'`'+"2") -as "Type"
$requestItemsType = $requestItemsType.MakeGenericType( @( ("System.string" -as "Type"), ($wrt)))
$ri = [Activator]::CreateInstance($requestItemsType)
$ri.Add("TaskLog",$writeRequests)
于 2012-08-15T20:00:57.393 に答える