gpt4 book ai didi

c# - 使用包含另一个对象数组的对象的反射读取属性

转载 作者:可可西里 更新时间:2023-11-01 08:21:35 27 4
gpt4 key购买 nike

如何在 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 的对象。我想从上到下读取所有属性并将名称/值对存储在字典/列表项中。我能够为值(value)、自定义、枚举类型做到这一点。我被一堆对象困住了。不知道该怎么做。

最佳答案

试试这段代码:

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());
}
}
}
}
}

我已经测试了这段代码,它通过反射正确地解析了数组。

关于c# - 使用包含另一个对象数组的对象的反射读取属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4879197/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com