值在枚举列表中 [英] Value is in enum list
本文介绍了值在枚举列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,我有这个枚举:
public enum UserStatus
{
未验证,
活动,
已删除,
暂停,
禁止
}
现在我想检查如果状态在(未验证,活动)
我知道这是有效的:
bool ok = status == UserStatus.Unverified || status == UserStatus.Active;
但是必须有一个更优雅的方式来写这个。
此任务的主题非常相似,但这是处理标志枚举,这不是一个标志枚举。
提前感谢
解决方案
这是一个扩展方法,可以帮助很多情况。
public static class Ext
{
public static bool In< T>(this T val,params T [] values)其中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));
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
}
Now I want to check if status in (Unverified, Active)
I know this works:
bool ok = status == UserStatus.Unverified || status == UserStatus.Active;
But there has to be a more elegant way to write this.
The topic of this queston is very similar, but that's dealing with flags enums, and this is not a flags enum.
Thanks in advance.
解决方案
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);
}
}
Usage:
Console.WriteLine(1.In(2, 1, 3));
Console.WriteLine(1.In(2, 3));
Console.WriteLine(UserStatus.Active.In(UserStatus.Removed, UserStatus.Banned));
这篇关于值在枚举列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文