C# Enums - Check Flags against a Mask

你。 提交于 2019-12-05 04:18:50

You can turn the condition around, and check if the composite enum has the flag, rather than checking the flag for the composite, like this:

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");
}

This prints Readable.

Yes, hasFlag checks if every bit field (flag) is set.

Rather than treating Readable as a composite of all the protections that include Read in the name, can you turn the composition around? E.g.

[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 like:

myMemoryProtection.HasFlag(MemoryProtection.Read)

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);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!