获取属性的属性

Get properties of properties

所以,我有兴趣通过反射获取 class 的所有属性......以及 class 类型属性的所有属性(递归)。

我使用如下代码通过反射成功获得了第一级属性:

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

在工厂里:

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;
}

显然(在我看来是这样),然后我会在 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);
        }
      }
   }

如评论中所述,为反射获取新的“基础对象”,即启动反射的“第二级”不起作用,它returns null。 我在这个阶段真的很挣扎,虽然我已经走了这么远并且已经很接近了(我认为)。

Whosebug 帮帮我, 你是我唯一的希望。

编辑: 所以,回答数据是什么样子的问题:

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

如果我要在 A 的实例上调用工厂,我会创建一个 PrimitiveDealer。 如果我们在 B 的实例上调用它,我会得到一个 CompositeDealer,它又具有一个 primitiveDealer。 另请注意,我需要传递实例的实际 属性 对象(因为我需要操作它)而不是新对象。

不是根据 属性 类型调用不同的函数来获取对象的属性,而是函数应该使用我们想要获取其属性的对象的实例调用自身。

object o = Activator.CreateInstance(property.PropertyType)

递归调用获取该对象属性的函数。

编辑:如果您需要实际对象,请确保将其转换为正确的类型。

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