gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 03:31:11 24 4
gpt4 key购买 nike

我有一个像这样的枚举:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com