目前我面临的问题是我需要创建一个包含任何类型案例的 Dictionary 实例。类型由方法的参数传递。 我不只是想创建一个动态或对象类型的字典,因为这会通过使用我的库来面对用户很多转换问题。 我也不能使用简单的构造函数,因为我的方法用真实的数据(存储在文件中)填充 Dictionary。按类型变量创建特定字典很重要。 这就是我的想法:
public static Dictionary<dynamic, dynamic> createDict(Type type1, Type type2)
{
// how to create the dictionary?
// im filling my dictionary with any data ...
return dict;
}
这里用户调用我的方法:
Dictionary<string, int> dict = MyLib.createDict(typeof(string), typeof(int));
// or
MyOwnType myInstance = new MyOwnType();
Dictionary<string, MyOwnType> dict = MyLib.createDict(typeof(string), myInstance.GetType());
最佳答案
Type dictType = typeof(Dictionary<, >).MakeGenericType(Type1, Type2);
var dict = Activator.CreateInstance(dictType);
- 获取
Dictionary
的类型
- 使用
MakeGenericType
创建具有指定类型的泛型类型
- 使用
Activator.CreateInstance
创建泛型类型的实例
关于c# - 如何在类型变量中创建任何类型的字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11717264/