【发布时间】:2013-08-19 21:29:13
【问题描述】:
我一直在研究C#中的反射,想知道如果我使用带有键值的字典可以创建一个带有变量的对象,该变量带有字典中每个键的名称及其值,那个字典的键值。
我有一个相反的方法,它从字典中提取一个对象,这个字典包含键和类属性及其值,属性的值。
如果可能的话,我想知道如何做到这一点。
下面是我的方法,它提取一个对象的字典:
protected Dictionary<String, String> getObjectProperty(object objeto)
{
Dictionary<String, String> dictionary = new Dictionary<String, String>();
Type type = objeto.GetType();
FieldInfo[] field = type.GetFields();
PropertyInfo[] myPropertyInfo = type.GetProperties();
String value = null;
foreach (var propertyInfo in myPropertyInfo)
{
if (propertyInfo.GetIndexParameters().Length == 0)
{
value = (string)propertyInfo.GetValue(objeto, null);
value = value == null ? null : value;
dictionary.Add(propertyInfo.Name.ToString(), value);
}
}
return dictionary;
}
【问题讨论】:
-
你的意思是“动态”类型的对象吗?还是创建新类型?
-
您使用什么版本的 .NET 框架?
-
对象已经存在,退出这个函数时,我只需要将它的结果强制转换(myObject)到现有对象。 .NET 4.0
-
可能这就是您要查找的内容 [Convert Dictionary
To Anonymous Object?][1] [1]: stackoverflow.com/questions/7595416/…
标签: c# reflection system.reflection