2

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

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

于 2011-04-08T15:47:37.537 回答