简体   繁体   English

有没有办法检查C#中特定值的类的属性

[英]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. 然后使用forforeach循环检查值。

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.

相关问题 C#优雅方式检查所有浅属性是否为null(或任何属性不为null) - C# elegant way to check if all shallow properties are null (or any property is not null) C# 有没有更好的方法来检查 object 中是否有超过 2 个属性不是 null - C# is there any better way to check if more than 2 properties in an object is not null C#检查属性内部或外部的值? - C# Check value inside or outside of properties? 检查三个具有某些值的属性或它们在C#中全部为NULL的更好方法 - Better way to check three properties having some value or all of them are NULL in C# C#在类构造函数中分配类属性有什么好处吗? - C# Is there any benefit to assigning class properties in the class constructor? 如何检查嵌套列表是否包含特定值C# - How to check if a nested list contains a particular value C# 在编码方面以XML格式化特定C#类的最简单方法 - Simplest way to serialize a particular C# class in XML in terms of coding 有什么方法可以通过重新编译使C#应用程序属性持久化吗? - Is there any way to make C# application properties persist through recompiles? 有什么方法可以在 C# 中使用 XML 轴属性? - Any way to use XML axis properties in C#? C# 索引器属性 - 有什么方法可以虚拟化 get 而不是 set 方法? - C# Indexer properties - Any way to virtualize the get and not the set method?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM