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

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

    To check if for example AB is set I can do this:

    if((letter & Letters.AB) == Letters.AB)

    Is there a simpler way to check if any of the flags of a combined flag constant are set than the following?

    This checks that both A and B are set, and ignores whether any other flags are set.

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

    This checks that either A or B is set, and ignores whether any other flags are set or not.

    This can be simplified to:

    if(letter & Letters.AB)
    

    Here's the C for binary operations; it should be straightforward to apply this to C#:

    enum {
         A = 1,
         B = 2,
         C = 4,
         AB = A | B,
         All = AB | C,
    };
    
    int flags = A|C;
    
    bool anything_and_a = flags & A;
    
    bool only_a = (flags == A);
    
    bool a_and_or_c_and_anything_else = flags & (A|C);
    
    bool both_ac_and_anything_else = (flags & (A|C)) == (A|C);
    
    bool only_a_and_c = (flags == (A|C));
    

    Incidentally, the naming of the variable in the question's example is the singular 'letter', which might imply that it represents only a single letter; the example code makes it clear that its a set of possible letters and that multiple values are allowed, so consider renaming the variable 'letters'.

提交回复
热议问题