简体   繁体   English

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

[英]Using reflection read properties of an object containing array of another object

How can I read the properties of an object that contains an element of array type using reflection in c#. 如何使用c#中的反射读取包含数组类型元素的对象的属性。 If I have a method called GetMyProperties and I determine that the object is a custom type then how can I read the properties of an array and the values within. 如果我有一个名为GetMyProperties的方法,并且我确定该对象是自定义类型,那么我该如何读取数组的属性及其中的值。 IsCustomType is method to determine if the type is custom type or not. 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); 
        } 
    } 
}

The scenario is, I have an object of ArrayClass and ArrayClass has two properties: 场景是,我有一个ArrayClass和ArrayClass的对象有两个属性:

-string Id
-DeptArray[] depts

DeptArray is another class with 2 properties: DeptArray是另一个具有2个属性的类:

-string code 
-string value

So, this methods gets an object of ArrayClass. 因此,此方法获取ArrayClass的对象。 I want to read all the properties to top-to-bottom and store name/value pair in a dictionary/list item. 我想在字典/列表项中读取所有属性从上到下并存储名称/值对。 I am able to do it for value, custom, enum type. 我能够为价值,定制,枚举类型做到这一点。 I got stuck with array of objects. 我被一堆物体困住了。 Not sure how to do it. 不知道怎么做。

Try this code: 试试这段代码:

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

I've tested this code and it resolves arrays through reflection correctly. 我已经测试了这段代码,它通过正确的反射来解析数组。

You'll need to retrieve the property value object and then call GetType() on it. 您需要检索属性值对象,然后在其上调用GetType()。 Then you can do something like this: 然后你可以做这样的事情:

var type = pinfo.GetGetMethod().Invoke(obj, new object[0]).GetType();
if (type.IsArray)
{
    Array a = (Array)obj;
    foreach (object arrayVal in a)
    {
        // reflect on arrayVal now
        var elementType = arrayVal.GetType();
    }
}

FYI -- I pulled this code from a recursive object formatting method (I would use JSON serialization for it now). 仅供参考 - 我从递归对象格式化方法中提取此代码(我现在将使用JSON序列化)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM