生成字典,C#反射动态对象 [英] Generate dynamic object from dictionary with C # Reflection
问题描述
我已经研究了一下关于C#反射和想知道如果我用的键,值的字典可以创建与字典中和值的每个键的名称中的变量对象,该字典的键值。
我有刚好相反,它从字典中提取对象的方法,这本词典包含键和类属性及其值,属性的值。
我不知道是否有可能如何做到这一点。
下面是我的方法,提取对象的字典:
保护字典<字符串,字符串> getObjectProperty(对象objeto)
{
&字典LT;字符串,字符串>词典=新词典<字符串,字符串>();
$ B $型B型= objeto.GetType();
的FieldInfo []字段= type.GetFields();
的PropertyInfo [] = myPropertyInfo type.GetProperties();
字符串值= NULL;
的foreach(在myPropertyInfo VAR的PropertyInfo)
{
如果(propertyInfo.GetIndexParameters()。长度== 0)
{
值=(字符串)propertyInfo.GetValue(objeto,NULL);
值=价值== NULL?空:值;
dictionary.Add(propertyInfo.Name.ToString(),价值);
}
}
返回字典;
}
如果你已经有一本字典,我会避免反光,只是使用 DynamicObject
例如:
公共类DynamicDictionary:DynamicObject
{
私人只读字典<字符串对象>字典;
公共DynamicDictionary(词典<字符串对象>字典)
{
this.dictionary =字典;
}
公众覆盖布尔TryGetMember(
GetMemberBinder粘结剂,out对象结果)
{
返回dictionary.TryGetValue(binder.Name,出结果) ;
}
公众覆盖布尔TrySetMember(
SetMemberBinder粘结剂,对象的值)
{
词典[binder.Name] =价值;
返回真;
}
}
这可以按如下方式使用:
动态X =新DynamicDictionary(
新字典<字符串对象> {{姓名,彼得}});
Console.WriteLine(x.Name);
I've been researching a bit about reflections in C # and would like to know if I use a dictionary with keys-values can create an object with the variable with the name of each key in the dictionary and their values, the key value of that dictionary.
I have a method that does the opposite, that extracts an object from a dictionary, this dictionary contains the keys and the class properties and their values, the value of the properties.
I wonder how to do this if possible.
Below is my method, which extracts a dictionary of an object:
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;
}
If you've already got a dictionary, I'd avoid reflection and just use DynamicObject
For example:
public class DynamicDictionary : DynamicObject
{
private readonly Dictionary<string, object> dictionary;
public DynamicDictionary(Dictionary<string, object> dictionary)
{
this.dictionary = dictionary;
}
public override bool TryGetMember(
GetMemberBinder binder, out object result)
{
return dictionary.TryGetValue(binder.Name, out result);
}
public override bool TrySetMember(
SetMemberBinder binder, object value)
{
dictionary[binder.Name] = value;
return true;
}
}
Which can be used as follows:
dynamic x = new DynamicDictionary(
new Dictionary<string, object> {{"Name", "Peter"}});
Console.WriteLine(x.Name);
这篇关于生成字典,C#反射动态对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!