如何删除OR'd枚举的项目?
我有一个枚举像:
public enum Blah { RED = 2, BLUE = 4, GREEN = 8, YELLOW = 16 } Blah colors = Blah.RED | Blah.BLUE | Blah.YELLOW; 
我怎样才能从variables的颜色去除蓝色?
 你需要& “BLUE”的~ (补)相配合。 
 补码操作符本质上是反转或“翻转”给定数据types的所有位。 因此,如果使用具有某个值的AND运算符( & )(让我们将该值称为“X”)和一个或多个置位的补码(让我们将这些位称为Q及其补码~Q ) X & ~Q清除在X中设置的任何位,并返回结果。 
 所以要删除或清除BLUE位,请使用以下语句: 
 colorsWithoutBlue = colors & ~Blah.BLUE colors &= ~Blah.BLUE // This one removes the bit from 'colors' itself 
您也可以指定多个位来清除,如下所示:
 colorsWithoutBlueOrRed = colors & ~(Blah.BLUE | Blah.RED) colors &= ~(Blah.BLUE | Blah.RED) // This one removes both bits from 'colors' itself 
或者交替地…
 colorsWithoutBlueOrRed = colors & ~Blah.BLUE & ~Blah.RED colors &= ~Blah.BLUE & ~Blah.RED // This one removes both bits from 'colors' itself 
所以总结一下:
-  
X | QX | Q设置X | Q(位) -   
X & ~Q清除X & ~Q(位) -   〜X翻转/反转
X所有位 
其他答案是正确的,但要从上面特别删除蓝色,你会写:
 colors &= ~Blah.BLUE; 
  And not …………………………. 
 Blah.RED | Blah.YELLOW == (Blah.RED | Blah.BLUE | Blah.YELLOW) & ~Blah.BLUE; 
认为这可能对像我这样偶然发现的其他人有用。
要小心如何处理任何枚举值,你可能会设置一个值== 0(有时它可以是一个枚举未知或空闲状态是有帮助的)。 依靠这些位操作操作会导致问题。
另外,当你有枚举值是2值的其他幂的组合,例如
 public enum Colour { None = 0, // default value RED = 2, BLUE = 4, GREEN = 8, YELLOW = 16, Orange = 18 // Combined value of RED and YELLOW } 
在这些情况下,像这样的扩展方法可能会派上用场:
 public static Colour UnSet(this Colour states, Colour state) { if ((int)states == 0) return states; if (states == state) return Colour.None; return states & ~state; } 
另外还有处理组合值的equivilent IsSet方法(虽然有点怪异)
 public static bool IsSet(this Colour states, Colour state) { // By default if not OR'd if (states == state) return true; // Combined: One or more bits need to be set if( state == Colour.Orange ) return 0 != (int)(states & state); // Non-combined: all bits need to be set return (states & state) == state; } 
xor(^)怎么样?
鉴于你试图删除的标志存在,它会工作..如果没有,你将不得不使用&。
 public enum Colour { None = 0, // default value RED = 2, BLUE = 4, GREEN = 8, YELLOW = 16, Orange = 18 // Combined value of RED and YELLOW } colors = (colors ^ Colour.RED) & colors; 
你可以使用这个:
 colors &= ~Blah.RED;