值是枚举列表 [英] Value is in enum list
本文介绍了值是枚举列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个很基本的问题:我如何可以检查一个给定值包含在枚举值列表
I have a fairly basic question: How can I check if a given value is contained in a list of enum values?
例如,我有这样的枚举:
For example, I have this enum:
public enum UserStatus
{
Unverified,
Active,
Removed,
Suspended,
Banned
}
现在我想在检查状态(未验证,活动)
我知道这个作品:
bool ok = status == UserStatus.Unverified || status == UserStatus.Active;
但必须有一个更优雅的方式来写这个。
But there has to be a more elegant way to write this.
这queston 是非常相似的,但是这涉及标志枚举,这不是一个标志枚举。
The topic of this queston is very similar, but that's dealing with flags enums, and this is not a flags enum.
在此先感谢。
推荐答案
下面是一个扩展的方法,帮助了很多很多情况下。
Here is an extension method that helps a lot in a lot of circumstances.
public static class Ext
{
public static bool In<T>(this T val, params T[] values) where T : struct
{
return values.Contains(val);
}
}
用法:
Console.WriteLine(1.In(2, 1, 3));
Console.WriteLine(1.In(2, 3));
Console.WriteLine(UserStatus.Active.In(UserStatus.Removed, UserStatus.Banned));
这篇关于值是枚举列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文