小编Elt*_*sta的帖子

使用C#Reflection从字典生成动态对象

我一直在研究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;
}
Run Code Online (Sandbox Code Playgroud)

c# reflection system.reflection

6
推荐指数
2
解决办法
2万
查看次数

标签 统计

c# ×1

reflection ×1

system.reflection ×1