C#枚举 - 检查标记反对面膜 [英] C# Enums - Check Flags against a Mask

查看:119
本文介绍了C#枚举 - 检查标记反对面膜的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下枚举标志:

[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)
}

现在我有我需要检查它是否易读枚举实例。如果我用下面的code:

Now i have an enum instance that I need to check if it's readable. If I use the following code:

myMemoryProtection.HasFlag(MemoryProtection.Readable)

因为我觉得HasFlag检查是否有充分的标志它总是返回false在我的情况。我需要的东西典雅避免做这样的:

It always returns false in my case because I think HasFlag check if it has every flag. I need something elegant to avoid doing this:

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

我该怎么办呢?

How can I do it?

推荐答案

您可以把病情各地,并检查复合枚举的标志,而不是检查该标志的复合材料,是这样的:

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)) {
    ...
}

下面是一个例子:

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

这版画

这篇关于C#枚举 - 检查标记反对面膜的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆