使用包含另一个对象数组的对象的反射读取属性

Sri*_*ddy 12 c# arrays reflection object propertyinfo

如何使用c#中的反射读取包含数组类型元素的对象的属性.如果我有一个名为GetMyProperties的方法,并且我确定该对象是自定义类型,那么我该如何读取数组的属性及其中的值.IsCustomType是确定类型是否为自定义类型的方法.

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

场景是,我有一个ArrayClass和ArrayClass的对象有两个属性:

-string Id
-DeptArray[] depts
Run Code Online (Sandbox Code Playgroud)

DeptArray是另一个具有2个属性的类:

-string code 
-string value
Run Code Online (Sandbox Code Playgroud)

因此,此方法获取ArrayClass的对象.我想在字典/列表项中读取所有属性从上到下并存储名称/值对.我能够为价值,定制,枚举类型做到这一点.我被一堆物体困住了.不知道怎么做.

Evg*_*vgK 16

试试这段代码:

public static void GetMyProperties(object obj)
{
  foreach (PropertyInfo pinfo in obj.GetType().GetProperties())
  {
    var getMethod = pinfo.GetGetMethod();
    if (getMethod.ReturnType.IsArray)
    {
      var arrayObject = getMethod.Invoke(obj, null);
      foreach (object element in (Array) arrayObject)
      {
        foreach (PropertyInfo arrayObjPinfo in element.GetType().GetProperties())
        {
          Console.WriteLine(arrayObjPinfo.Name + ":" + arrayObjPinfo.GetGetMethod().Invoke(element, null).ToString());
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我已经测试了这段代码,它通过正确的反射来解析数组.