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

前端 未结 2 1565
我寻月下人不归
我寻月下人不归 2020-12-09 19:08

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

相关标签:
2条回答
  • 2020-12-09 19:30

    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).

    0 讨论(0)
  • 2020-12-09 19:43

    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.

    0 讨论(0)
提交回复
热议问题