如何在 c# 中使用反射读取包含数组类型元素的对象的属性。如果我有一个名为 GetMyProperties 的方法并且我确定该对象是自定义类型,那么我如何读取数组的属性和其中的值。IsCustomType 是确定类型是否为自定义类型的方法。
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 有两个属性:
-string Id
-DeptArray[] depts
DeptArray 是另一个具有 2 个属性的类:
-string code
-string value
因此,此方法获取 ArrayClass 的对象。我想从上到下读取所有属性并将名称/值对存储在字典/列表项中。我能够为值、自定义、枚举类型做到这一点。我被一系列对象困住了。不知道该怎么做。