我有一个枚举:
public enum Blah
{
RED = 2,
BLUE = 4,
GREEN = 8,
YELLOW = 16
}
Blah colors = Blah.RED | Blah.BLUE | Blah.YELLOW;
我如何从可变颜色中移除蓝色?
我有一个枚举:
public enum Blah
{
RED = 2,
BLUE = 4,
GREEN = 8,
YELLOW = 16
}
Blah colors = Blah.RED | Blah.BLUE | Blah.YELLOW;
我如何从可变颜色中移除蓝色?
当前回答
你可以用这个:
colors &= ~Blah.RED;
其他回答
你可以用这个:
colors &= ~Blah.RED;
其他答案都是正确的,但是为了从上面的选项中去除蓝色,你可以这样写:
colors &= ~Blah.BLUE;
那么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;
要切换标志,您可以使用duckface操作符,而不必使用~反转位
color ^= Color.Red; // unset Color.Red
or
color ^= (Color.Red | Color.Blue); // toggle both Red and Blue
但是,这将切换标志,而不是清除它。
正如@daniil-palii所提到的那样,编辑以确保正确性
为了简化标志枚举,并通过避免倍数来更好地读取,我们可以使用位移位。 (摘自一篇好文章《结束关于旗帜的大争论》)
[FLAG]
Enum Blah
{
RED = 1,
BLUE = 1 << 1,
GREEN = 1 << 2,
YELLOW = 1 << 3
}
还要清除所有比特
private static void ClearAllBits()
{
colors = colors & ~colors;
}