Using reflection to set a property of a property of an object

后端 未结 3 762
一生所求
一生所求 2021-01-12 19:24

I\'ve got two classes.

public class Class1 {
   public string value {get;set;}
}

public class Class2 {
   public Class1 myClass1Object {get;set;}
}
<         


        
3条回答
  •  自闭症患者
    2021-01-12 20:07

    I was looking for answers to the case where to Get a property value, when the property name is given, but the nesting level of the property is not known.

    Eg. if the input is "value" instead of providing a fully qualified property name like "myClass1Object.value".

    Your answers inspired my recursive solution below:

    public static object GetPropertyValue(object source, string property)
    {
        PropertyInfo prop = source.GetType().GetProperty(property);
        if(prop == null)
        {
          foreach(PropertyInfo propertyMember in source.GetType().GetProperties())
          { 
             object newSource = propertyMember.GetValue(source, null);
             return GetPropertyValue(newSource, property);
          }
        }
        else
        {
           return prop.GetValue(source,null);
        }
        return null;
    }
    

提交回复
热议问题