获取C#中属性的值

时间:2018-12-10 05:49:05

标签: c#

这是一个非常简单的问题。 例如以下代码:

        if(o == null)
        {
            o = new { };
        }
        PropertyInfo[] p1 = o.GetType().GetProperties();
        foreach(PropertyInfo pi in p1)
        {}

但是像这样:

ModelA.ModelB.ModelC.ModelD.ModelE

如何通过反映ModelA来获得ModelE的价值

3 个答案:

答案 0 :(得分:3)

here中有一个解决方案:

使用辅助方法:

public static class ReflectionHelper
{
    public static Object GetPropValue(this Object obj, String propName)
    {
        string[] nameParts = propName.Split('.');
        if (nameParts.Length == 1)
        {
            return obj.GetType().GetProperty(propName).GetValue(obj, null);
        }

        foreach (String part in nameParts)
        {
            if (obj == null) { return null; }

            Type type = obj.GetType();
            PropertyInfo info = type.GetProperty(part);
            if (info == null) { return null; }

            obj = info.GetValue(obj, null);
        }
        return obj;
    }
}

然后可以像这样使用该方法:

ModelA obj = new ModelA { */....*/ };
obj.GetPropValue("modelB.modelC.modelD.modelE");

请注意,您应该将属性名称传递给函数,而不是类名称。

答案 1 :(得分:0)

我认为这些都是匿名类型,因为否则您可以对ModelE的类型执行GetProperties()。

因此,基本上,您必须像接下来的5个循环

foreach (PropertyInfo pi1 in o1.GetType().GetProperties())
{
    if (pi.Name = "ModelB") // or some other criterion
    {
        o2 = pi1.GetValue(o1);
        foreach (PropertyInfo pi2 in o2.GetType().GetProperties())
        {
            if (pi.Name = "ModelC") // or some other criterion
            {
                o3 = pi1.GetValue(o2);
                // and so on
            }
        }
    }
}

答案 2 :(得分:0)

使用嵌套函数执行以下操作:

    var testObj = new
{
    nameA = "A",
    ModelB = new
    {
        nameB = "B",
        ModelC = new
        {
            NameC = "C",
        }
    }
};
var result = ParseProperty(testObj, null, "ModelA");

public Dictionary<string, object> ParseProperty(object o, Dictionary<string, object> result, string preFix = null)
{
    result = result ?? new Dictionary<string, object>();

    if (o == null) return result;

    Type t = o.GetType();
    //primitive type or value type  or string or nested return
    if (t.IsPrimitive || t.IsValueType || t.FullName == "System.String" || t.IsNested) return result;

    var proerties = o.GetType().GetProperties();
    foreach (var property in proerties)
    {
        var value = property.GetValue(o);
        result.Add($"{preFix}.{property.Name}", value);
        //nested call
        ParseProperty(value, result, $"{preFix}.{property.Name}");
    }
    return result;
}