如何创建具有类型变量中的任何类型的字典?

mod*_*diX 3 .net c# dictionary types dynamic

目前我面临的问题是我需要创建一个具有任何类型案例的字典实例。类型由方法的参数传递。我不仅仅是想创建一个动态或对象类型字典,因为这会导致用户使用我的库面临很多转换问题。我也无法使用简单的构造函数,因为我的方法实际上用数据(存储在文件中)填充字典。通过类型变量创建特定的字典非常重要。这就是我的想法:

public static Dictionary<dynamic, dynamic> createDict(Type type1, Type type2)
{
    // how to create the dictionary?
    // im filling my dictionary with any data ...
    return dict;
}
Run Code Online (Sandbox Code Playgroud)

这里用户调用我的方法:

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());
Run Code Online (Sandbox Code Playgroud)

Tho*_*mas 7

Type dictType = typeof(Dictionary<, >).MakeGenericType(Type1, Type2);
var dict = Activator.CreateInstance(dictType);
Run Code Online (Sandbox Code Playgroud)
  • 获取类型Dictionary
  • 使用指定类型创建泛型类型MakeGenericType
  • 使用以下命令创建泛型类型的实例Activator.CreateInstance

  • 如何将项目“添加”到新创建的词典中?`dict.Add("keyName", "value")` 不会编译,因为 `dict` 被识别为只是一个通用的 `object`。 (3认同)