我有一个对象,它包含对象和其他类型,其中一个是其活动状态的布尔值。我想要做的是迭代对象及其属性,以检查包含此布尔值的每个属性对象的布尔值。这就是我到目前为止所知道的:
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发布于 2019-07-28 19:45:44
您可以使用简单的linq来实现相同的功能,而不需要递归:
var activeProperties = objectType.GetProperties().Where(prop => prop.Name == property && (Boolean)item.GetValue(Object) == true);上面将包含所有活动属性,您可以随意处理它们。
递归更慢,也占用了更多的堆栈。递归的主要优点是,对于像树遍历这样的问题,它使算法变得更容易或更“优雅”--这不是你在这里要做的。
只需使用link,您就可以根据需要嵌套\钻取对象的深度。
附注:
而不是
(Boolean)item.GetValue(Object) != true请使用:
(Boolean)item.GetValue(Object) == false你比鲍比·拉什利( Bobby Lashley )更让我困惑(如果有人在看这里的笨蛋的话)。
发布于 2019-07-28 19:52:35
您的递归逻辑是正确的。更确切地说,问题是您在item上调用checkStatus,它是一个propertyInfo对象,而不是属性。不是在item上调用checkStatus,而是在item.GetValue(object)上调用它。
https://stackoverflow.com/questions/57240394
复制相似问题