简体   繁体   中英

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. I want to inform user in case all of these 50 properties are false.

One way is to use 50 if and if conditions.other way is reflection which seems overkill for this thing. Please suggest some other way. I am using .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.

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:

private List<Boolean> props;

public bool IsExpired
{
    get { return !props.Any(p => p); }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM