首页 > 解决方案 > 通过对象递归迭代

问题描述

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

    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

标签: c#

解决方案


您的递归逻辑是正确的。问题在于您正在调用checkStatusitem这是一个propertyInfo对象,而不是属性。与其调用checkStatusitem不如调用它item.GetValue(object)


推荐阅读