How to remove an item for a OR'd enum?

后端 未结 7 1701
后悔当初
后悔当初 2020-12-22 18:17

I have an enum like:

public enum Blah
{
    RED = 2,
    BLUE = 4,
    GREEN = 8,
    YELLOW = 16
}

Blah colors = Blah.RED | Blah.BLUE | Blah.YELLOW;


        
相关标签:
7条回答
  • 2020-12-22 19:07

    You need to & it with the ~ (complement) of 'BLUE'.

    The complement operator essentially reverses or 'flips' all bits for the given data type. As such, if you use the AND operator (&) with some value (let's call that value 'X') and the complement of one or more set bits (let's call those bits Q and their complement ~Q), the statement X & ~Q clears any bits that were set in Q from X and returns the result.

    So to remove or clear the BLUE bits, you use the following statement:

    colorsWithoutBlue = colors & ~Blah.BLUE
    colors &= ~Blah.BLUE // This one removes the bit from 'colors' itself
    

    You can also specify multiple bits to clear, as follows:

    colorsWithoutBlueOrRed = colors & ~(Blah.BLUE | Blah.RED)
    colors &= ~(Blah.BLUE | Blah.RED) // This one removes both bits from 'colors' itself
    

    or alternately...

    colorsWithoutBlueOrRed = colors & ~Blah.BLUE & ~Blah.RED
    colors &= ~Blah.BLUE & ~Blah.RED // This one removes both bits from 'colors' itself
    

    So to summarize:

    • X | Q sets bit(s) Q
    • X & ~Q clears bit(s) Q
    • ~X flips/inverts all bits in X
    0 讨论(0)
提交回复
热议问题