小编典典

如何在C#中比较标志?

c#

我下面有一个标志枚举。

[Flags]
public enum FlagTest
{
    None = 0x0,
    Flag1 = 0x1,
    Flag2 = 0x2,
    Flag3 = 0x4
}

我无法使if语句评估为true。

FlagTest testItem = FlagTest.Flag1 | FlagTest.Flag2;

if (testItem == FlagTest.Flag1)
{
    // Do something,
    // however This is never true.
}

我如何才能做到这一点?


阅读 410

收藏
2020-05-19

共1个答案

小编典典

在.NET 4中,有一个新方法Enum.HasFlag。这使您可以编写:

if ( testItem.HasFlag( FlagTest.Flag1 ) )
{
    // Do Stuff
}

IMO更具可读性。

.NET源表明这与接受的答案具有相同的逻辑:

public Boolean HasFlag(Enum flag) {
    if (!this.GetType().IsEquivalentTo(flag.GetType())) {
        throw new ArgumentException(
            Environment.GetResourceString(
                "Argument_EnumTypeDoesNotMatch", 
                flag.GetType(), 
                this.GetType()));
    }

    ulong uFlag = ToUInt64(flag.GetValue()); 
    ulong uThis = ToUInt64(GetValue());
    // test predicate
    return ((uThis & uFlag) == uFlag); 
}
2020-05-19