PropertyInfo GetValue在递归期间抛出错误

Sri*_*ddy 3 c# reflection propertyinfo

当我尝试在运行时在C#程序中检索对象的值时,我得到"对象与目标类型不匹配".

public void GetMyProperties(object obj)
{
  foreach(PropertyInfo pinfo in obj.GetType().GetProperties())
  {
    if(!Helper.IsCustomType(pinfo.PropertyType))
    {
      string s = pinfo.GetValue(obj, null); //throws error during recursion call
      propArray.Add(s);
    }
    else
    {
      object o = pinfo.PropertyType;
      GetMyProperties(o);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我传递了我的Class BrokerInfo的一个对象,它有一个Broker类型的属性,其中inturn有属性 - FirstName和LastName(为简单起见所有字符串).

- BrokerInfo
  - Broker
    - FirstName
    - LastName
Run Code Online (Sandbox Code Playgroud)

我试图递归检查自定义类型并尝试获取其值.我可以做类似的事情:

- Broker
  - FirstName
  - LastName
Run Code Online (Sandbox Code Playgroud)

请帮忙.

更新:能够在leppie的帮助下解决它:这是修改后的代码.

public void GetMyProperties(object obj)
{
  foreach(PropertyInfo pinfo in obj.GetType().GetProperties())
  {
    if(!Helper.IsCustomType(pinfo.PropertyType))
    {
      string s = pinfo.GetValue(obj, null); 
      propArray.Add(s);
    }
    else
    {
      object o = pinfo.GetValue(obj, null);
      GetMyProperties(o);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

IsCustom是我检查类型是否是客户类型的方法.这是代码:

public static bool IsCustomType(Type type)
{
    //Check for premitive, enum and string
    if (!type.IsPrimitive && !type.IsEnum && type != typeof(string))
    {
        return true;
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

lep*_*pie 5

为什么要深入研究类型,而不是实例?

具体在这里:

  object o = pinfo.PropertyType;
  GetMyProperties(o);
Run Code Online (Sandbox Code Playgroud)

它应该看起来像:

  var o = pinfo.GetValue(obj, null);
  GetMyProperties(o);
Run Code Online (Sandbox Code Playgroud)