使用包含另一个对象的数组对象的反射读取属性 [英] Using reflection read properties of an object containing array of another object
问题描述
我怎样才能读取包含在C#中使用反射阵列类型的元素一个对象的属性。如果我有一个方法叫GetMyProperties,我确定该物体是那么自定义类型我怎么可以读取一个数组的属性和范围内的值。 IsCustomType是方法来确定的类型是自定义类型或不
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);
}
}
}
的情况是,我有ArrayClass的对象,并ArrayClass有两个属性:
The scenario is, I have an object of ArrayClass and ArrayClass has two properties:
-string Id
-DeptArray[] depts
DeptArray是2个属性另一个类:
DeptArray is another class with 2 properties:
-string code
-string value
因此,该方法得到ArrayClass的一个目的。我想读的所有属性顶部至底部和存储名称/值对的字典/列表项。我能做到这一点的价值,自定义,枚举类型。我被套牢的对象数组。不知道如何做到这一点。
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.
推荐答案
试试这个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());
}
}
}
}
}
我测试过这个code,它通过反射正确解析阵列。
I've tested this code and it resolves arrays through reflection correctly.
这篇关于使用包含另一个对象的数组对象的反射读取属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!