删除枚举标志 [英] Removing enum flags

查看:138
本文介绍了删除枚举标志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

老实说,我对删除枚举标志感到有些困惑.

I'm a little bit puzzled by the removal of enum flags to be perfectly honest.

让我举个例子,假设我们有一个看起来像这样的枚举

Let me make an example, let's say we have an enum that looks like this

[Flags]
enum Letter 
{
    A = 1, // 1
    B = 2, // 10
    C = 4  // 100
}

现在,如果我想使变量保留标志Letter.AB,则可以执行foo = Letter.A | Letter.B.现在这对我来说很有意义,我可以计算出这一点,这将很有意义:

Now if I want to make a variable hold the flags Letter.AB I could do foo = Letter.A | Letter.B. Now this makes sense to me, I can calculate this and it will make sense:

   01
OR 10
 = 11 = 3 = 1 + 2 = A + B = AB

在删除标志时,我很困惑,直觉上我想使用 XOR 运算符这样做,就像这样:

When it comes to removing flags, I am puzzled however, intuitively what I would like to do is use the XOR operator to do so, like this:

bar = Letter.A | Letter.B | Letter.C // Set bar to ABC
// Now let's remove everything but Letter.C
bar = bar ^ (Letter.A | Letter.B)

手工计算得出的结果:

    111
XOR 011
  = 100 = 4 = C = ABC - (A + B) = 7 - (1 + 2)

但是,这似乎并不是人们在删除枚举标志时所要做的,他们使用 AND 运算符,这对我来说绝对没有意义.使用 XOR 运算符删除枚举标志有什么缺点吗?显然这里有些东西我看不到,因此详细的说明将不胜感激! :)

But this isn't what people seem to do when they are removing enum flags, they use the AND operator which makes absolutely no sense to me. Is there any drawback to using the XOR operator for removing enum flags? There must obviously be something I'm not seeing here, so a detailed clarification would be appreciated greatly! :)

推荐答案

是的,XOR运算符的问题在于,除非您知道,否则您将拥有其余所有标志只会翻转它们.因此,您的XOR操作不是删除所有内容,而是C",而是切换A和B的值". (因此,例如,如果输入为"A,C",则您将以"B,C"结尾.)

Yes, the problem with the XOR operator is that unless you know that you've got all the rest of the flags, it will just flip them. So your XOR operation isn't "remove all but C" - it's "toggle the values of A and B". (So if the input was "A,C" you'd end up with "B,C", for example.)

&是因为它是 masking .基本思想是,获得一个仅包含所需位的值,然后将该值与输入值进行按位与运算即可将其屏蔽.

& is used because it's masking. The basic idea is that you get a value which contains just the bits you want, and then a bitwise AND of that value with your input value masks it.

要删除一个特定标志(而不是保留该特定标志),通常可以使用~运算符来创建除该标志之外的所有标志"的掩码.例如:

To remove one specific flag (rather than retaining that specific flag), you'd typically use the ~ operator to create a mask of "all but that flag". For example:

var mask = ~Letter.A;
var newValue = originalValue & mask; // All previous values other than A

这篇关于删除枚举标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆