c# - 通过对象递归迭代
问题描述
我有一个包含对象和其他类型的对象,其中一个是其活动状态的布尔值。我想要做的是遍历对象及其属性以检查包含此布尔值的每个属性对象的布尔值。这是我到目前为止所拥有的:
public void checkStatus(object Object, string property)
{
Type objectType = Object.GetType();
PropertyInfo[] propertiesInfo = objectType.GetProperties();
foreach (var item in propertiesInfo) {
if (item.Name == property && (Boolean)item.GetValue(Object) == true)
{
Console.WriteLine(item + " is active");
checkStatus((object)item, property);
}
else if (item.Name == property && (Boolean)item.GetValue(Object) != true)
{
Console.WriteLine(item + " is not active.");
checkStatus((object)item, property);
}
else {
Console.WriteLine("Property does not exist in" + item);
}
}
}
只检查第一级,不再进一步。想法?
这就是它需要的第一个数据位:
Boolean IsActive is active
Property does not exist inSystem.Reflection.MemberTypes MemberType
Property does not exist inSystem.String Name
Property does not exist inSystem.Type DeclaringType
Property does not exist inSystem.Type ReflectedType
Property does not exist inInt32 MetadataToken
Property does not exist inSystem.Reflection.Module Module
Property does not exist inSystem.Type PropertyType
Property does not exist inSystem.Reflection.PropertyAttributes Attributes
Property does not exist inBoolean CanRead
Property does not exist inBoolean CanWrite
Property does not exist inBoolean IsSpecialName
Property does not exist inSystem.Reflection.MethodInfo GetMethod
Property does not exist inSystem.Reflection.MethodInfo SetMethod
Property does not exist inSystem.Collections.Generic.IEnumerable`1[System.Reflection.CustomAttributeData] CustomAttributes
Property does not exist inSystem.Nullable`1[System.Int64] CardNumber
Property does not exist inConsoleApp1.Client Client
Property does not exist inConsoleApp1.Account Account
解决方案
您的递归逻辑是正确的。问题在于您正在调用checkStatus
,item
这是一个propertyInfo
对象,而不是属性。与其调用checkStatus
,item
不如调用它item.GetValue(object)
。
推荐阅读
- javascript - 如何获取 Leap Motion 的活动实例并在 A-Frame 中使用运动播放
- ruby - 红宝石汇率回报
- java - Spring Reactor:这个 Flux 会内存溢出吗?
- sql - 需要为 db_name 在整周中选择最大 LAG_MIN 并计算其整周的出现次数
- python - 向框架添加滚动条,框架不断扩展并向下滚动不起作用
- insert - 如何使用相同的编辑页面打开新记录(插入)与现有(编辑)的页面
- c++ - C++/Win32 - 如何迭代特定进程的线程列表并将起始地址解析为模块?
- sumo - 在examples/sumo/grid.py上模拟,有几个检测器,如何获取数据
- c# - C# 列表
.Sort - 为什么默认实现有这么好的性能? - javascript - 使引导轮播中的图像响应?