[英]Is there any way to check for properties of a class for a particular value in c#
I have a License class.There are 50 boolean properties and some timestamp properties. 我有一个License类,有50个布尔属性和一些timestamp属性。 I want to inform user in case all of these 50 properties are false.
如果这50个属性全部为false,我想通知用户。
One way is to use 50 if and if conditions.other way is reflection which seems overkill for this thing. 一种方法是使用if和if条件,另一种方法是反射,对于此问题似乎有些过分了。 Please suggest some other way.
请提出其他建议。 I am using .Net framework 3.5
我正在使用.Net Framework 3.5
You could certainly do this with reflection: 您当然可以通过反射来做到这一点:
var values = from prop in typeof(License).GetProperties()
where prop.PropertyType == typeof(bool)
select (bool) prop.GetValue(instance, null);
if (!values.Any(x => x))
{
// Nope, everything's false
}
I'm not sure what you want to do about the timestamp properties... 我不确定您要如何处理时间戳属性...
Can you change the strucutre of the class? 您可以更改班级的结构吗?
In that case if the boolean values are connected somehow you can use the following: 在这种情况下,如果以某种方式连接了布尔值,则可以使用以下命令:
And then to check the values just use a for
or foreach
loop. 然后使用
for
或foreach
循环检查值。
Besides that, reflection is your friend. 除此之外,反思是您的朋友。
You should look at an Indexed Property . 您应该查看索引属性 。 You could encapsulate the check into a read-only property of License:
您可以将支票封装到License的只读属性中:
private List<Boolean> props;
public bool IsExpired
{
get { return !props.Any(p => p); }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.