简体   繁体   English

标志枚举奇怪的值

[英]Flags enum strange values

[Flags]
public enum Direction
{
    None = 0x0000,
    Left = 0x0001,
    Right = 0x0002,
    Up = 0x0004,
    Down = 0x0008,
    Forward = 0x0016,
    Backward = 0x0032
}

Really confused, I'm using using this enum in an if statement like so: 真的很困惑,我在if语句中使用这个枚举,如下所示:

if ((enumValues & Direction.Forward) == Direction.Forward)
{
    // do stuff
}

to check if it contains a flag inside the collection. 检查它是否在集合内包含一个标志。

if ((enumValues & Direction.Right) == Direction.Forward)
{
    // do stuff
}

Keeps running this if ( Direction.Right ) code despite not containing the Right flag inside the collection, I've even debugged it with breaks and the value doesn't contain Direction.Right but it's still returning true and running the snippet. 尽管未在集合中包含Right标志,但仍继续运行if ( Direction.Right )代码,我什至用中断对其进行调试,并且该值不包含Direction.Right但仍返回true并运行代码段。

Have I set up my enum wrong or am I querying the values wrong? 我设置的枚举错误还是我查询的值错误?

I don't use flags normally I just figured it would be a good use of them. 我通常不使用标志,我只是认为这是对它们的一种好用法。

Seeing how you have defined your enum: 查看您如何定义枚举:

None = 0x0000,
Left = 0x0001,
Right = 0x0002,
Up = 0x0004,
Down = 0x0008,
Forward = 0x0016,
Backward = 0x0032

You are confusing hexadecimal and decimal numbers. 您混淆十六进制和十进制数字。

In a [Flags] enum, the binary representation of the values of your enum should be something like this: [Flags]枚举中,枚举值的二进制表示应如下所示:

0000 0000 0000 0000 0000 0000 0000 0001
0000 0000 0000 0000 0000 0000 0000 0010
0000 0000 0000 0000 0000 0000 0000 0100
0000 0000 0000 0000 0000 0000 0000 1000

Which in decimal, are powers of 2: 1, 2, 4, 8, 16 etc 以十进制表示的是2、1、2、4、8、16等的幂

But the way you are writing the values start with 0x , which denotes a hexadecimal value. 但是,您编写值的方式以0x ,它表示一个十六进制值。 So you are actually setting the values for the enum case as the hex numbers 1, 2, 4, 8 and 16. 因此,您实际上是将枚举大小写的值设置为十六进制数字 1、2、4、8和16。

You should remove those 0x : 您应该删除那些0x

None = 0,
Left = 1,
Right = 2,
Up = 4,
Down = 8,
Forward = 16,
Backward = 32

For hex you should define values like this: 对于十六进制,应定义如下值:

Forward = 0x0010,
Backward = 0x0020

Or in decimal: 或十进制:

Forward = 16,
Backward = 32

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM