Getting Nested Object Property Value Using Reflection

前端 未结 11 2026
甜味超标
甜味超标 2020-12-03 06:55

I have the following two classes:

public class Address
{
    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }
    public         


        
11条回答
  •  我在风中等你
    2020-12-03 07:32

    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");
    

提交回复
热议问题