如何删除OR'd枚举的项目? [英] How to remove an item for a OR'd enum?

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

问题描述

我有一个枚举:

  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 //这个从颜色本身中删除位

您还可以指定要清除的多个位,如下所示:

  colorsWithoutBlueOrRed = colors& 〜(Blah.BLUE | Blah.RED)
colors& =〜(Blah.BLUE | Blah.RED)//这个从颜色本身去除两个位元

或者交替地...

  colorsWithoutBlueOrRed =颜色& 〜Blah.BLUE& 〜Blah.RED 
colors& =〜Blah.BLUE& 〜Blah.RED //这个从颜色本身删除了两个位

所以总结一下: / p>


  • X | Q 设置位 Q

  • X& 〜Q 清除位 Q

  • 〜X 翻转/翻转 X中的所有位


I have an enum like:

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

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

How could I remove the color blue from the variable colors?

解决方案

You need to & it with the ~ (complement) of 'BLUE'.

The complement operator essentially reverses or 'flips' all bits for the given data type. As such, if you use the AND operator (&) with some value (let's call that value 'X') and the complement of one or more set bits (let's call those bits Q and their complement ~Q), the statement X & ~Q clears any bits that were set in Q from X and returns the result.

So to remove or clear the BLUE bits, you use the following statement:

colorsWithoutBlue = colors & ~Blah.BLUE
colors &= ~Blah.BLUE // This one removes the bit from 'colors' itself

You can also specify multiple bits to clear, as follows:

colorsWithoutBlueOrRed = colors & ~(Blah.BLUE | Blah.RED)
colors &= ~(Blah.BLUE | Blah.RED) // This one removes both bits from 'colors' itself

or alternately...

colorsWithoutBlueOrRed = colors & ~Blah.BLUE & ~Blah.RED
colors &= ~Blah.BLUE & ~Blah.RED // This one removes both bits from 'colors' itself

So to summarize:

  • X | Q sets bit(s) Q
  • X & ~Q clears bit(s) Q
  • ~X flips/inverts all bits in X

这篇关于如何删除OR'd枚举的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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