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 08:07

I use this method to get the values from properties (unlimited number of nested property) as below:

"Property"

"Address.Street"

"Address.Country.Name"

    public static object GetPropertyValue(object src, string propName)
    {
        if (src == null) throw new ArgumentException("Value cannot be null.", "src");
        if (propName == null) throw new ArgumentException("Value cannot be null.", "propName");

        if(propName.Contains("."))//complex type nested
        {
            var temp = propName.Split(new char[] { '.' }, 2);
            return GetPropertyValue(GetPropertyValue(src, temp[0]), temp[1]);
        }
        else
        {
            var prop = src.GetType().GetProperty(propName);
            return prop != null ? prop.GetValue(src, null) : null;
        }
    }

Here the Fiddle: https://dotnetfiddle.net/PvKRH0

查看更多
SAY GOODBYE
3楼-- · 2020-01-29 08:10

This will work for unlimited number of nested property.

public object GetPropertyValue(object obj, string propertyName)
{
    var _propertyNames = propertyName.Split('.');

    for (var i = 0; i < _propertyNames.Length; i++)
    {
        if (obj != null)
        {
            var _propertyInfo = obj.GetType().GetProperty(_propertyNames[i]);
            if (_propertyInfo != null)
                obj = _propertyInfo.GetValue(obj);
            else
                obj = null;
        }
    }

    return obj;
}

Usage:

GetPropertyValue(_employee, "Firstname");
GetPropertyValue(_employee, "Address.State");
GetPropertyValue(_employee, "Address.Country.Name");
查看更多
Fickle 薄情
4楼-- · 2020-01-29 08:15

Get Nest properties e.g., Developer.Project.Name

private static System.Reflection.PropertyInfo GetProperty(object t, string PropertName)
            {
                if (t.GetType().GetProperties().Count(p => p.Name == PropertName.Split('.')[0]) == 0)
                    throw new ArgumentNullException(string.Format("Property {0}, is not exists in object {1}", PropertName, t.ToString()));
                if (PropertName.Split('.').Length == 1)
                    return t.GetType().GetProperty(PropertName);
                else
                    return GetProperty(t.GetType().GetProperty(PropertName.Split('.')[0]).GetValue(t, null), PropertName.Split('.')[1]);
            }
查看更多
Rolldiameter
5楼-- · 2020-01-29 08:16

A Modified version of above to get the multilevel nested properties

private static System.Reflection.PropertyInfo GetProperty(object t, string PropertName, out object Value)
        {
            Value = "";
            var v = t.GetType().GetProperties();
            if (t.GetType().GetProperties().Count(p => p.Name == PropertName.Split('.')[0]) == 0)
                //throw new ArgumentNullException(string.Format("Property {0}, is not exists in object {1}", PropertName, t.ToString()));
                return null;
            if (PropertName.Split('.').Length == 1)
            {
                var Value1 = t.GetType().GetProperty(PropertName).GetValue(t, null);
                Value = Value1;//.ToString();
                return t.GetType().GetProperty(PropertName);
            }
            else
            {
                //return GetProperty(t.GetType().GetProperty(PropertName.Split('.')[0]).GetValue(t, null), PropertName.Split('.')[1], out Value);
                return GetProperty(t.GetType().GetProperty(PropertName.Split('.')[0]).GetValue(t, null), PropertName.Substring(PropertName.IndexOf('.') + 1, PropertName.Length - PropertName.IndexOf('.') - 1), out Value);
            }
        }
查看更多
登录 后发表回答