Wall-E
Wall-E

Reputation: 21

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.

Edit: So, answering the question what the data would look like:

class A {
   int primitiveProp {get;}
}
class B {
   A compositeProp {get;}
}

If I were to call the Factory on an instance of A, I'd make a PrimitiveDealer. If we call it on an instance of B, I'd get a CompositeDealer, which in turn has a primitiveDealer. Also note that I need the actual property object of the passed instance (since I need to manipulate it) rather than a new object.

Upvotes: 1

Views: 636

Answers (1)

london2020
london2020

Reputation: 26

Instead of calling different functions to get the properties of your object, dependent on the property type, the function should then call itself with an instance of the object we want to get the properties of.

object o = Activator.CreateInstance(property.PropertyType)

Recursively call the function which gets the properties of this object.

Edit: If you instead need the actual object, ensure to cast it to the correct type.

Type compProp = (Type)propInfo.GetValue(obj);  

Upvotes: 1

Related Questions