mercredi 2 décembre 2020

Get properties of properties

So, I am interested in getting all properties of a class via reflection ... and all properties of class-type properties (recursively).

I managed to get the first level of properties via reflections with a code like this:

foreach (var property in Target.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
  var foobar = Factory.GetDealer(Target, property.Name);
}

and in the factory:

public static BaseDealer GetDealer(Object obj, string property) 
{
  var prop = obj.GetType().GetProperty(property);
  if (prop == null)
  {
    return null;
  }

  if (prop.PropertyType.IsPrimitive)
  {
    return GetPrimitivDealer(obj, property, Type.GetTypeCode(prop.PropertyType));
  }

  if (prop.PropertyType.IsClass)
  {
    return new CompositeDealer(obj, prop);
  }

  return null;
}

Obviously (in my mind that is), I'd then have something like this in the CompositeDealer:

   public CompositeDealer(Object obj, PropertyInfo propInfo)
   {      
      ComponentDealers = new List<BaseDealer>();
      Object compProp = propInfo.GetValue(obj);  // The new "origin" object for reflection, this does not work
      foreach (var property in compProp.GetType().GetProperties())
      {
        var dealer = Factory.GetDealer(compProp, property.Name);
        if (dealer != null)
        {
          ComponentDealer.Add(dealer);
        }
      }
   }

As noted in the comment, getting the new "base object" for reflection, that is to start the "second level" of reflection does not work, it returns null. I really struggle at this stage although I came so far and am pretty close (I think).

Help me StackOverflow, you're my only hope.





Aucun commentaire:

Enregistrer un commentaire