值是枚举列表列表

由网友(用爸妈的套,套媳妇)分享简介:我有一个很基本的问题:我如何可以检查一个给定值包含在枚举值列表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 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));
阅读全文

相关推荐

最新文章