How to check if any flags of a flag combination are set?

前端 未结 16 639
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 17:24

Let\'s say I have this enum:

[Flags]
enum Letters
{
     A = 1,
     B = 2,
     C = 4,
     AB = A | B,
     All = A | B | C,
}

To check i

16条回答
  •  迷失自我
    2020-11-29 17:48

    You can use this extension method on enum, for any type of enums:

    public static bool IsSingle(this Enum value)
    {
        var items = Enum.GetValues(value.GetType());
        var counter = 0;
        foreach (var item in items)
        {
            if (value.HasFlag((Enum)item))
            {
                counter++;
            }
            if (counter > 1)
            {
                return false;
            }
        }
        return true;
    }
    

提交回复
热议问题