vendredi 16 avril 2021

C# - How to reach grand child of class using reflection

public class A
{
   public B b { get; set;}
}
public class B
{
   public C c { get; set;}
}
public class C
{
   public string Name { get; set; }
}

I need to reach the value of C.Name dynamically using reflection. With my limited imagination I can only reach the second layer with the code below

 Type type = a.GetType();
 PropertyInfo[] properties = type.GetProperties();
 foreach (PropertyInfo property in properties)
 {
     var subObject = type.GetProperty(property.Name).GetValue(a); // this is b
     foreach (var subProperty in subObject.GetType().GetProperties())
     {
          var propertyValue = subProperty.GetValue(subObject);
     }
 }

What should be my next step?





Aucun commentaire:

Enregistrer un commentaire