鉴于以下代码,我正在尝试根据我拥有的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)
答案 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的文档。