Getting Nested Object Property Value Using Reflection

前端 未结 11 2013
甜味超标
甜味超标 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: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);
    }
    

提交回复
热议问题