简体   繁体   中英

How do I test if a bitwise enum contains any values from another bitwise enum in C#?

For instance. I have the following enum

[Flags]
public enum Stuff
{
   stuff1=1,
   stuff2=2,
   stuff3=4,
   stuff4=8
}

So I set mystuff to

mystuff = Stuff.stuff1|Stuff.stuff2;

then I set hisstuff to

hisstuff = Stuff.stuff2|Stuff.stuff3;

How do I now test if these overlap -ie hisstuff and mystuff both contain at least one of the same enum values?

And also if there are multiple ways to do it which is the most efficient? (This is for a game)

Simple:

if((x & y) != 0) {...}

This does a bitwise "and", then tests for any intersection.

To get the values that are set in both values, you use the and ( & ) operator:

mystuff & hisstuff

This gives you a new value with only the overlapping values, in your example only Stuff.stuff2 . To check if any of the values overlap, you check if it is non-zero:

if ((mystuff & hisstuff) != 0) ...

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