Vb.net 使用Activator.CreateInstance创建并创建字典实例(K,V)
给出下面的代码,我正试图基于我拥有的Vb.net 使用Activator.CreateInstance创建并创建字典实例(K,V),vb.net,types,generics,activator,Vb.net,Types,Generics,Activator,给出下面的代码,我正试图基于我拥有的ItemType变量创建字典(字符串?)的新实例。如何构造DictType,以便使用Activator创建我所要的类型的实例 Dim ItemType As Type ' Data type of dictionary value Dim DictType As Type = ???? ' Dictionary(of String, ItemType)
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)
您正在寻找的是
GetType
方法。这将从声明的/可绑定的类型名称返回一个Type
实例。比如说
Dim dictType = GetType(Dictionary(Of String, Integer))
Dim newDict = Activator.CreateInstance(dictType)
编辑
以下是在编译时并非所有类型都已知时创建字典(键、值)
类型的版本
Dim itemType As Type = ...
Dim dictRaw = GetType(Dictionary(Of ,))
Dim dictType = dictRaw.MakeGenericType(GetType(String), itemType)
Dim value = Activator.CreateInstance(dictType)
假设您有一个类型为
type
的方法参数或局部变量,其名称为typeVariable
。那么答案是:
Dim dictType = GetType(Dictionary(Of ,)).MakeGenericType(GetType(String), typeVariable)
有关示例,请参阅文档(),包括一个使用字典的示例。但是第二种类型在编译时未知,因此这不起作用。@phoog,明白了。更新了我的答案以显示该场景