我只想知道是否设置了一个枚举标志,而不是哪一个。我目前的想法是检查它是否是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.
可以找到更多信息在这个答案中有类似的问题: stackoverflow/a/1662162/2404788 。
More information can be found in this answer to a similar question: stackoverflow/a/1662162/2404788.
有关位操作的更多信息,请访问 http:// en .wikipedia / wiki / Bitwise_operation
For more information about bit operations go to en.wikipedia/wiki/Bitwise_operation
更多推荐
如何检查是否设置了多个枚举标志?
发布评论