简体   繁体   English

如何检查枚举标志是否与另一个枚举一起出现?

[英]How to check if an enum flag is raised alongside with another enum?

I have the following enum:我有以下枚举:

[Flags]
public enum Permissions
{
    None = 0x0000,
    All = 0xFFFF
}

If either None or All are raised, no other flag should be raised.如果出现 None 或 All ,则不应出现其他标志。
How do I check if either None or All are raised and nothing else?我如何检查是否提出了 None 或 All ,而没有其他问题?

In a flags enum, None should be zero, and All should be the cumulative bitwise sum.在 flags 枚举中, None应该是零,并且All应该是累积的按位和。 This makes the maths pretty easy, then:这使得数学很容易,然后:

if(value == Permissions.None || value == Permissions.All) {...}

maybe written as a switch if you prefer...如果您愿意,可以写成switch ...

However, in the general case, you can test for a complete flags match (against any number of bits) with:但是,在一般情况下,您可以使用以下方法测试完整的标志匹配(针对任意数量的位):

if((value & wanted) == wanted) {...}

and to test for any overlap (ie any common bits - wanted needs to be non-zero):并测试任何重叠(即任何公共位 - wanted非零):

if((value & wanted) != 0) {...}
if(value|Permissions.None)==Permissions.None;

This can check Permissions.None is raised.这可以检查 Permissions.None 被提出。 The rest can be done in the same manner. rest 可以以相同的方式完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM