Using reflection read properties of an object containing array of another object

我与影子孤独终老i 提交于 2019-11-27 02:50:06

问题


How can I read the properties of an object that contains an element of array type using reflection in 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. IsCustomType is method to determine if the type is custom type or not.

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:

-string Id
-DeptArray[] depts

DeptArray is another class with 2 properties:

-string code 
-string value

So, this methods gets an object of 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.


回答1:


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.




回答2:


You'll need to retrieve the property value object and then call GetType() on it. 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).



来源:https://stackoverflow.com/questions/4879197/using-reflection-read-properties-of-an-object-containing-array-of-another-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!