Getting Nested Object Property Value Using Reflection

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

    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.

提交回复
热议问题