Getting Nested Object Property Value Using Reflect

2020-01-29 07:30发布

I have the following two classes:

public class Address
{
    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Zip { get; set; }
}

public class Employee
{
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }
    public Address EmployeeAddress { get; set; }
}

I have an instance of the employee class as follows:

    var emp1Address = new Address();
    emp1Address.AddressLine1 = "Microsoft Corporation";
    emp1Address.AddressLine2 = "One Microsoft Way";
    emp1Address.City = "Redmond";
    emp1Address.State = "WA";
    emp1Address.Zip = "98052-6399";

    var emp1 = new Employee();
    emp1.FirstName = "Bill";
    emp1.LastName = "Gates";
    emp1.EmployeeAddress = emp1Address;

I have a method which gets the property value based on the property name as follows:

public object GetPropertyValue(object obj ,string propertyName)
{
    var objType = obj.GetType();
    var prop = objType.GetProperty(propertyName);

    return prop.GetValue(obj, null);
}

The above method works fine for calls like GetPropertyValue(emp1, "FirstName") but if I try GetPropertyValue(emp1, "Address.AddressLine1") it throws an exception because objType.GetProperty(propertyName); is not able to locate the nested object property value. Is there a way to fix this?

10条回答
叛逆
2楼-- · 2020-01-29 07:51

This will work for level 1 and level 2 object properties e.g. Firstname and Address.AddressLine1

public object GetPropertyValue(object obj, string propertyName)
{
    object targetObject = obj;
    string targetPropertyName = propertyName;

    if (propertyName.Contains('.'))
    {
        string[] split = propertyName.Split('.');
        targetObject = obj.GetType().GetProperty(split[0]).GetValue(obj, null);
        targetPropertyName = split[1];
    }

    return targetObject.GetType().GetProperty(targetPropertyName).GetValue(targetObject, null);
}
查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-01-29 07:52

I have a problem with struct type in static class, So I must use this method GetNestedType, this is example code if you know property name, If you want to getAll you can use GetNestedTypes

ExpandoObject in this example just use for dynamic add property and value

private void ExtractValuesFromAppconstants(string keyName)
        {
            Type type = typeof(YourClass);
            var examination = type.GetNestedType(keyName);
            if (examination != null)
            {    
                var innerTypes = examination.GetNestedTypes();
                foreach (var innerType in innerTypes)
                {
                    Console.Writeline($"{innerType.Name}")
                }
            }
        }
查看更多
趁早两清
4楼-- · 2020-01-29 07:55
public object GetPropertyValue(object obj, string propertyName)
{
    foreach (var prop in propertyName.Split('.').Select(s => obj.GetType().GetProperty(s)))
       obj = prop.GetValue(obj, null);

    return obj;
}

Thanks, I came here looking for an answer to the same problem. I ended up modifying your original method to support nested properties. This should be more robust than having to do nested method calls which could end up being cumbersome for more than 2 nested levels.

查看更多
可以哭但决不认输i
5楼-- · 2020-01-29 07:55

Yet another variation to throw out there. Short & sweet, supports arbitrarily deep properties, handles null values and invalid properties:

public static object GetPropertyVal(this object obj, string name) {
    if (obj == null)
        return null;

    var parts = name.Split(new[] { '.' }, 2);
    var prop = obj.GetType().GetProperty(parts[0]);
    if (prop == null)
        throw new ArgumentException($"{parts[0]} is not a property of {obj.GetType().FullName}.");

    var val = prop.GetValue(obj);
    return (parts.Length == 1) ? val : val.GetPropertyVal(parts[1]);
}
查看更多
手持菜刀,她持情操
6楼-- · 2020-01-29 07:55

I made an extension method on type for this propose:

public static class TypeExtensions
{
    public static PropertyInfo GetSubProperty(this Type type, string treeProperty, object givenValue)
    {
        var properties = treeProperty.Split('.');
        var value = givenValue;

        foreach (var property in properties.Take(properties.Length - 1))
        {
            value = value.GetType().GetProperty(property).GetValue(value);

            if (value == null)
            {
                return null;
            }
        }

        return value.GetType().GetProperty(properties[properties.Length - 1]);
    }

    public static object GetSubPropertyValue(this Type type, string treeProperty, object givenValue)
    {
        var properties = treeProperty.Split('.');
        return properties.Aggregate(givenValue, (current, property) => current.GetType().GetProperty(property).GetValue(current));
    }
}
查看更多
爷、活的狠高调
7楼-- · 2020-01-29 08:01
var address = GetPropertyValue(GetPropertyValue(emp1, "Address"), "AddressLine1");

Object Employee doesn't have a single property named "Address.AddressLine1", it has a property named "Address", which itself has a property named "AddressLine1".

查看更多
登录 后发表回答