2011-04-08 18 views
2

鑑於下面的代碼,我試圖根據我有的ItemType變量創建Dictionary(Of String, ??)的新實例。我該如何構建DictType,以便我可以使用Activator來創建我之後類型的實例?使用Activator.CreateInstance創建字典(K,V)的實例

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

回答

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) 
+0

但第二種類型在編譯時不知道,所以這不起作用。 – phoog 2011-04-08 15:43:35

+0

@phoog,gotcha。更新我的答案以顯示該情景 – JaredPar 2011-04-08 15:48:15

相關問題