我可以一次查询C#对象的所有布尔属性,寻找单个匹配吗?

Bob*_*way 0 c# linq

想象的对象:

public class ImaginaryObject
{
    int objectId { get; set; }
    string name { get; set; }
    bool b1 { get; set; }
    bool b2 { get; set; }
    bool b3 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

有没有什么方法可以编写单个查询,而无需命名对象上的任何字段,返回一个布尔值,如果对象上的任何布尔值为true,则为true,否则为false?

(标记为Linq,因为我怀疑这将成为答案的一部分,如果可能的话)

Far*_*yev 5

您可以使用命名空间中的方法GetType()和动态获取类型对象所属的详细信息.GetProperties()System.Reflection

var booleanProperties = imaginaryObject.GetType()
     .GetProperties()
     .Where(prop => prop.PropertyType == typeof(Boolean));

foreach(var prop in booleanProperties) 
{
    if((bool)prop.GetValue(imaginaryObject, null) == true)
        return true;
}
Run Code Online (Sandbox Code Playgroud)

或者简单地使用LINQ:

 var isAnyTrue= imaginaryObject.GetType()
       .GetProperties()
       .Where(prop => prop.PropertyType == typeof(Boolean))
       .Any(prop => (bool)prop.GetValue(imaginaryObject, null));
Run Code Online (Sandbox Code Playgroud)