c# - 如何删除 OR 枚举的项目?

标签 c# enums

我有一个像这样的枚举:

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

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

如何从可变颜色中去除蓝色?

最佳答案

您需要 &它与 ~ “蓝色”的(补语)。

补码运算符本质上是反转或“翻转”给定数据类型的所有位。因此,如果您使用 AND运算符 ( & ) 与某个值(我们称该值为“X”)和一个或多个设置位的补码(我们称这些位为 Q 及其补码 ~Q ),语句 X & ~Q清除 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 | Q设置位 Q
  • X & ~Q清除位 Q
  • ~X翻转/反转 X 中的所有位

关于c# - 如何删除 OR 枚举的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4778166/

相关文章:

java - Java接口(interface)的switch语句

c++ - 在 C++ 中迭代枚举类的常用方法是什么?

java - 如何在没有实现的情况下将枚举公开给公共(public) API?

c# - 使 span 元素在中继器的 ItemBound 事件中可见

c# - 在 windows 中使用 linux 根库

c# - LINQ .FromSQL 错误 InvalidOperationException : Sequence contains more than one matching element

c# - Combobox 只显示一些comboxitems

c# - KeyedCollection 是否仅在 Key 确定其中项相等时才有意义?

java - 在 Java 中用更少的代码将枚举映射到另一个枚举

Java: `enum` 与 `String` 作为参数