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

前端 未结 16 629
佛祖请我去吃肉
佛祖请我去吃肉 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 could just check if the value is not zero.

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

    But I would consider it a better solution to introduce a new enumeration value with value zero and compare agains this enumeration value (if possible because you must be able to modify the enumeration).

    [Flags]
    enum Letters
    {
        None = 0,
        A    = 1,
        B    = 2,
        C    = 4,
        AB   =  A | B,
        All  = AB | C
    }
    
    if (letter != Letters.None) { }
    

    UPDATE

    Missread the question - fixed the first suggestion and just ignore the second suggestion.

    0 讨论(0)
  • 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)
    {
    }
    
    0 讨论(0)
  • 2020-11-29 17:51

    If you want to know if letter has any of the letters in AB you must use the AND & operator. Something like:

    if ((letter & Letters.AB) != 0)
    {
        // Some flag (A,B or both) is enabled
    }
    else
    {
        // None of them are enabled
    }
    
    0 讨论(0)
  • 2020-11-29 17:52

    Would this work for you?

    if ((letter & (Letters.A | Letters.B)) != 0)
    

    Regards,

    Sebastiaan

    0 讨论(0)
提交回复
热议问题