Getting Nested Object Property Value Using Reflection

前端 未结 11 2027
甜味超标
甜味超标 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:29

    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]);
    }
    

提交回复
热议问题