如何检查是否设置了多个枚举标志? [英] How do I check if more than one enum flag is set?

查看:116
本文介绍了如何检查是否设置了多个枚举标志?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想知道是否设置了一个枚举标志,而不是哪一个。我目前的想法是检查它是否是2的幂。有没有更好的方式内置枚举类型?

I just want to know if exactly one enum flag is set, not which ones. My current thinking is to check if it is a power of 2. Is there a better way built into enum types?

[Flags]
enum Foo
{
Flag1 = 0x01,
Flag2 = 0x02,
Flag3 = 0x04,
Flag4 = 0x08,
Flag5 = 0x10,
Flag6 = 0x20,
Flag7 = 0x40,
Flag8 = 0x80
}

private bool ExactlynOneFlagSet(Foo myFoo)
{
  var x = (byte) myFoo;
  return (x != 0) && ((x & (x - 1)) == 0); //Check if a power of 2
}

if(!ExactlynOneFlagSet(Foo myFoo))
{
   //Do something
}


推荐答案

它的一个位操作!

if ((myFoo & (myFoo -1)) != 0) //has more than 1 flag

该语句检查 myFoo 的值是否不是电源的两个。或者反之亦然,语句(myFoo&(myFoo -1))== 0 检查两个的权力。这个想法是,只有单个标志值才是两个。设置多个标志将导致两个值 myFoo 的无功。

The statement checks if the value of myFoo is not power of two. Or, vice versa, the statement (myFoo & (myFoo -1)) == 0 checks for power of two. The idea is that only single flag values will be power of two. Setting more than one flag will result in a non power of two value of myFoo.

可以找到更多信息在这个答案中有类似的问题: https://stackoverflow.com/a/1662162/2404788

More information can be found in this answer to a similar question: https://stackoverflow.com/a/1662162/2404788.

有关位操作的更多信息,请访问 http:// en .wikipedia.org / wiki / Bitwise_operation

For more information about bit operations go to http://en.wikipedia.org/wiki/Bitwise_operation

这篇关于如何检查是否设置了多个枚举标志?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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