如何比较 C# 中的标志? [英] How to Compare Flags in C#?

查看:21
本文介绍了如何比较 C# 中的标志?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面有一个标志枚举.

I have a flag enum below.

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

我无法使 if 语句的计算结果为真.

I cannot make the if statement evaluate to true.

FlagTest testItem = FlagTest.Flag1 | FlagTest.Flag2;

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

我怎样才能做到这一点?

How can I make this true?

推荐答案

在 .NET 4 中有一个新方法 Enum.HasFlag.这允许你写:

In .NET 4 there is a new method Enum.HasFlag. This allows you to write:

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

可读性更高,IMO.

.NET 源代码表明这与接受的答案执行相同的逻辑:

The .NET source indicates that this performs the same logic as the accepted answer:

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

这篇关于如何比较 C# 中的标志?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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