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)
Type dictType = typeof(Dictionary<, >).MakeGenericType(Type1, Type2);
var dict = Activator.CreateInstance(dictType);
Run Code Online (Sandbox Code Playgroud)
DictionaryMakeGenericTypeActivator.CreateInstance