使用包含另一个对象数组的对象的反射读取属性 [英] 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.
推荐答案
试试这个代码:
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.
这篇关于使用包含另一个对象数组的对象的反射读取属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!