C # Enums - Check flags against masks

I have the following listing flags:

[Flags] private enum MemoryProtection: uint { None = 0x000, NoAccess = 0x001, ReadOnly = 0x002, ReadWrite = 0x004, WriteCopy = 0x008, Execute = 0x010, ExecuteRead = 0x020, ExecuteReadWrite = 0x040, ExecuteWriteCopy = 0x080, Guard = 0x100, NoCache = 0x200, WriteCombine = 0x400, Readable = (ReadOnly | ReadWrite | ExecuteRead | ExecuteReadWrite), Writable = (ReadWrite | WriteCopy | ExecuteReadWrite | ExecuteWriteCopy) } 

Now I have an instance of enum that I need to check to see if it is readable. If I use the following code:

 myMemoryProtection.HasFlag(MemoryProtection.Readable) 

It always returns false in my case, because I think HasFlag checks to see if it has every flag. I need something elegant to not do this:

 myMemoryProtection.HasFlag(MemoryProtection.ReadOnly) || myMemoryProtection.HasFlag(MemoryProtection.ReadWrite) || myMemoryProtection.HasFlag(MemoryProtection.ExecuteRead) || myMemoryProtection.HasFlag(MemoryProtection.ExecuteReadWrite) 

How can i do this?

+6
source share
3 answers

You can enable this condition and check if the composite enum flag, and not check the flag for the composite, for example:

 if (MemoryProtection.Readable.HasFlag(myMemoryProtection)) { ... } 

Here is an example:

 MemoryProtection a = MemoryProtection.ExecuteRead; if (MemoryProtection.Readable.HasFlag(a)) { Console.WriteLine("Readable"); } if (MemoryProtection.Writable.HasFlag(a)) { Console.WriteLine("Writable"); } 

Prints Readable .

+7
source

Try bitwise operators:

 [TestMethod] public void FlagsTest() { MemoryProtection mp = MemoryProtection.ReadOnly | MemoryProtection.ReadWrite | MemoryProtection.ExecuteRead | MemoryProtection.ExecuteReadWrite; MemoryProtection value = MemoryProtection.Readable | MemoryProtection.Writable; Assert.IsTrue((value & mp) == mp); } 
+3
source

Yes, hasFlag checks to see if each field is set to a bit (flag).

Instead of viewing Readable as the totality of all the defenses that include Read in the title, can you turn the composition around? For instance.

 [Flags] private enum MemoryProtection: uint { NoAccess = 0x000, Read = 0x001, Write = 0x002, Execute = 0x004, Copy = 0x008, Guard = 0x010, NoCache = 0x020, ReadOnly = Read, ReadWrite = (Read | Write), WriteCopy = (Write | Copy), // etc. NoAccess = 0x800 } 

Then you can write code, for example:

 myMemoryProtection.HasFlag(MemoryProtection.Read) 
+3
source

Source: https://habr.com/ru/post/943584/


All Articles