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

前端 未结 16 633
佛祖请我去吃肉
佛祖请我去吃肉 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:45

    If it really annoys you, you can write a function like that:

    public bool IsSet(Letters value, Letters flag)
    {
        return (value & flag) == flag;
    }
    
    if (IsSet(letter, Letters.A))
    {
       // ...
    }
    
    // If you want to check if BOTH Letters.A and Letters.B are set:
    if (IsSet(letter, Letters.A & Letters.B))
    {
       // ...
    }
    
    // If you want an OR, I'm afraid you will have to be more verbose:
    if (IsSet(letter, Letters.A) || IsSet(letter, Letters.B))
    {
       // ...
    }
    

提交回复
热议问题