c# - 如何在类型变量中创建任何类型的字典?

标签 c# .net dynamic types dictionary

目前我面临的问题是我需要创建一个包含任何类型案例的 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/

相关文章:

c# - ASP.NET 的 Wordpress 等价物

c# - Java 和 .NET 3.5 之间进程间通信的最佳方法是什么?

c# - 为什么我的代码会抛出无效的转换异常? (C#)?

c# - ASP.Net MVC 3 和 System.Data.Entity?

.NET 部分类与继承

c# - 如何将 byte[] 反序列化为要在方法调用时转换的通用对象

c# - 使用 wpf 将形状添加到 Canvas 的最佳方法?

c# - 检测应用程序的最后一次运行在 c# 中已崩溃

C# 在相应的输入类型中返回零

c# - 如何调用动态类型的扩展方法?