首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >递归遍历对象

递归遍历对象
EN

Stack Overflow用户
提问于 2019-07-28 19:25:51
回答 2查看 69关注 0票数 0

我有一个对象,它包含对象和其他类型,其中一个是其活动状态的布尔值。我想要做的是迭代对象及其属性,以检查包含此布尔值的每个属性对象的布尔值。这就是我到目前为止所知道的:

代码语言:javascript
复制
    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);
            }
        }
    }

只检查第一级,不再进一步检查。想法?

这就是它想要的第一位数据:

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

发布于 2019-07-28 19:45:44

您可以使用简单的linq来实现相同的功能,而不需要递归:

代码语言:javascript
复制
var activeProperties = objectType.GetProperties().Where(prop => prop.Name == property && (Boolean)item.GetValue(Object) == true);

上面将包含所有活动属性,您可以随意处理它们。

递归更慢,也占用了更多的堆栈。递归的主要优点是,对于像树遍历这样的问题,它使算法变得更容易或更“优雅”--这不是你在这里要做的。

只需使用link,您就可以根据需要嵌套\钻取对象的深度。

附注:

而不是

代码语言:javascript
复制
(Boolean)item.GetValue(Object) != true

请使用:

代码语言:javascript
复制
(Boolean)item.GetValue(Object) == false

你比鲍比·拉什利( Bobby Lashley )更让我困惑(如果有人在看这里的笨蛋的话)。

票数 0
EN

Stack Overflow用户

发布于 2019-07-28 19:52:35

您的递归逻辑是正确的。更确切地说,问题是您在item上调用checkStatus,它是一个propertyInfo对象,而不是属性。不是在item上调用checkStatus,而是在item.GetValue(object)上调用它。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57240394

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档