簡體   English   中英

C#枚舉 - 檢查面具上的標志

[英]C# Enums - Check Flags against a Mask

我有以下枚舉標志:

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

現在我有一個枚舉實例,我需要檢查它是否可讀。 如果我使用以下代碼:

myMemoryProtection.HasFlag(MemoryProtection.Readable)

它總是在我的情況下返回false,因為我認為HasFlag檢查它是否有每個標志。 我需要優雅的東西來避免這樣做:

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

我該怎么做?

你可以轉動條件,檢查復合enum是否有標志,而不是檢查復合的標志,如下所示:

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

這打印Readable

是的, hasFlag檢查是否設置了每個位字段(標志)。

而不是將Readable視為包含Read in the name的所有保護的組合,你可以改變構圖嗎? 例如

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

然后你可以編寫如下代碼:

myMemoryProtection.HasFlag(MemoryProtection.Read)

嘗試按位運算符:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM