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

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

    There are two aproaches that I can see that would work for checking for any bit being set.

    Aproach A

    if (letter != 0)
    {
    }
    

    This works as long as you don't mind checking for all bits, including non-defined ones too!

    Aproach B

    if ((letter & Letters.All) != 0)
    {
    }
    

    This only checks the defined bits, as long as Letters.All represents all of the possible bits.

    For specific bits (one or more set), use Aproach B replacing Letters.All with the bits that you want to check for (see below).

    if ((letter & Letters.AB) != 0)
    {
    }
    

提交回复
热议问题