使用Activator.CreateInstance创建和实例字典(Of of K,V)

时间:2011-04-08 15:37:55

标签: vb.net types generics activator

鉴于以下代码,我正在尝试根据我拥有的Dictionary(Of String, ??)变量创建ItemType的新实例。如何构造DictType以便我可以使用Activator创建我所追求的类型的实例?

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

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:2)

假设您有一个类型为Type的方法参数或局部变量,其名称为typeVariable。然后答案是:

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

请参阅文档(http://msdn.microsoft.com/en-us/library/system.type.makegenerictype.aspx)以获取示例,包括使用Dictionary的文档。

相关问题