作者热门文章
- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我有一个像这样的枚举:
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/
我是一名优秀的程序员,十分优秀!