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

前端 未结 2 1564
我寻月下人不归
我寻月下人不归 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).

提交回复
热议问题