简体   繁体   中英

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.
How do I check if either None or All are raised and nothing else?

In a flags enum, None should be zero, and All should be the cumulative bitwise sum. This makes the maths pretty easy, then:

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

maybe written as a switch if you prefer...

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):

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

This can check Permissions.None is raised. The rest can be done in the same manner.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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