C#反射字典

标签 c# serialization reflection dictionary

假设我有这段代码:

Dictionary<String, String> myDictionary = new Dictionary<String, String>();
Type[] arguments = myDictionary.GetType().GetGenericArguments();

在我的程序中,myDictionary 是未知类型(它是从反序列化的 XML 返回的对象),但对于本题而言,它们是字符串。我想创建这样的东西:

Dictionary<arguments[0],arguments[1]> mySecondDictionary = new Dictionary<arguments[0],arguments[1]>();

显然,这是行不通的。 我在 MSDN 上搜索过,我看到他们正在使用 Activator 类,但我不明白。 也许更高级的人可以帮助我一点。

最佳答案

您可以像您提到的那样使用激活器类来从给定类型创建对象。 MakeGenericType方法允许您指定一个类型数组作为通用对象的参数,这正是您试图模拟的。

Dictionary<String, String> myDictionary = new Dictionary<String, String>();
Type[] arguments = myDictionary.GetType().GetGenericArguments();

Type dictToCreate = typeof(Dictionary<,>).MakeGenericType(arguments);
var mySecondDictionary = Activator.CreateInstance(dictToCreate);

上面的代码基本上没有意义,因为您事先知道字典是 String,String 但假设您有办法在运行时检测其他地方所需的类型,您可以使用最后两行来实例化该类型的字典。

关于C#反射字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17514927/

相关文章:

c++ - 运行时访问图书管理员类?

c# - 如何在Java中转换C# InnerText XPath方法?

c# - Android 上的屏幕触摸模拟

c# - 使用 LINQ 查询时,类具有无效的表达式项 "from"

PHP serialize() 未正确序列化 stdClass 对象

java - 关于用 Java 编写自定义类异常

c# - 从 .NET 代码中提取数据

c# - 如何在控制台应用程序 C# 中获取 server.Mappath

c# - 按回车键时在文本框上执行命令

c# - 命名空间 'Serializable' 中不存在类型或命名空间名称 'System'(是否缺少程序集引用?