HasFlag始终返回True [英] HasFlag always returns True

查看:122
本文介绍了HasFlag始终返回True的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一种方法可以检查我在一系列标志中是否有标志?

There is a way to check if I got a flag in a series of flag?

示例:

[Flags]
Enum TestEnum
{
  ALIVE, DEAD, ALMOSTDEAD, HURT, OTHERS

}
// check if is alive and has been hurt
TestEnum aTest = TestEnum.ALIVE | TestEnum.HURT
bool aTest2 = aTest.HasFlag(TestEnum.ALIVE)

但是 a.Test.HasFlag 始终返回true,即使没有TestEnum.ALIVE

But a.Test.HasFlag always returns true, even without the TestEnum.ALIVE

推荐答案

您当然可以像所有人一样使用 Enum.HasFlag 建议。但是,重要的是要确保您的枚举采用2的幂。两位的幂只有一个位,因此您的枚举应如下所示:

You can certainly use Enum.HasFlag like everyone has suggested. However, its important to make sure that your enumeration falls in powers of two. Powers of two have a single bit set, so your enumeration should look like this:

Enum TestEnum
{
    ALIVE = 1, DEAD = 2, ALMOSTDEAD = 4, HURT = 8, OTHERS = 16
}

之所以重要,是因为您正在比较位标志。在内存中,您的枚举标志将如下所示:

The reason this is important is because you are comparing the bit flags. In memory, your enum flags will look like this:

ALIVE      = 00001
DEAD       = 00010
ALMOSTDEAD = 00100
HURT       = 01000
OTHERS     = 10000

按位操作时比较,例如 DEAD | ALMOSTDEAD ,您正在执行以下操作:

When you do a bitwise compare, like DEAD | ALMOSTDEAD, you are doing this:

DEAD       = 00010
           OR
ALMOSTDEAD = 00100
------------------
RESULT     = 00110

由于结果>> 0,所以它为true。

Since the Result is > then 0, its true.

这篇关于HasFlag始终返回True的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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