2

以下のコードを考えると、私が持っている変数にDictionary(Of String, ??)基づいての新しいインスタンスを作成しようとしています。目的のタイプのインスタンスを作成するために使用できるようにするにItemTypeはどうすればよいですか?DictTypeActivator

                Dim ItemType As Type            ' Data type of dictionary value
                Dim DictType As Type = ????     ' Dictionary(of String, ItemType)
                Dim NewDict = Activator.CreateInstance(DictType)
4

2 に答える 2

2

あなたが探しているのはGetType方法です。Typeこれは、指定された/バインド可能な型名からインスタンスを返します。例えば

Dim dictType = GetType(Dictionary(Of String, Integer))
Dim newDict = Activator.CreateInstance(dictType)

編集

Dictionary(Of Key, Value)コンパイル時にすべての型が認識されていない場合に型を作成するバージョンは次のとおりです。

Dim itemType As Type = ...
Dim dictRaw = GetType(Dictionary(Of ,))
Dim dictType = dictRaw.MakeGenericType(GetType(String), itemType)
Dim value = Activator.CreateInstance(dictType)
于 2011-04-08T15:41:46.280 に答える
2

Typeという名前のメソッド パラメータまたはローカル変数があるとしtypeVariableます。次に、答えは次のとおりです。

Dim dictType = GetType(Dictionary(Of ,)).MakeGenericType(GetType(String), typeVariable)

Dictionary を使用した例など、ドキュメント ( http://msdn.microsoft.com/en-us/library/system.type.makegenerictype.aspx ) を参照してください。

于 2011-04-08T15:47:37.537 に答える