如何在c#中使用反射来读取包含数组类型元素的对象的属性.如果我有一个名为GetMyProperties的方法,我确定该对象是一个自定义类型,那么如何读取数组的属性和其中的值. IsCustomType是确定类型是否为自定义类型的方法.
@H_404_2@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有两个属性:
@H_404_2@-string Id -DeptArray[] deptsDeptArray是另一个有2个属性的类:
@H_404_2@-string code -string value所以,这个方法得到一个ArrayClass的对象.我想从字典/列表项中读取所有属性,从顶到底,存储名称/值对.我能够为value,custom,enum类型做.我被卡住了数组的对象.不知道该怎么做
解决方法
尝试这段代码:
@H_404_2@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());
}
}
}
}
}
我已经测试了这个代码,它通过反射来正确地解析了数组.