mercredi 20 octobre 2021

Recursively get private field value using reflection

I've got a deeply nested private fields chain which I'd like to iterate recursively to get the value of some target field.

How can this be done?

For example:

public class A
{
   private B b;
   public A(B b) { this.b = b; }
}

public class B
{
   private C[] cItems;
   public B(C[] cItems) { this.cItems = cItems; }
}

public class C
{
   private string target; // <-- get this value
   public C(int target) { this.target = val; }
}
public static void GetFieldValueByPath(object targetObj, string targetFieldPath)
{
   // how to do it?
}

Usage will be:

public void DoSomething(A a)
{
   var val = GetFieldValueByPath(a, "b.cItems[2].target");
}
  • Notes:
    • There is a related question about recursively getting properties, but not fields. But even then, it doesn't support array fields.
    • Related questions such as this one for getting fields are not recursive.




Aucun commentaire:

Enregistrer un commentaire