开发者

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 o开发者_开发问答ther 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:

  • Array
  • Dictionaries

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); }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜