[英]Flags Enum in binary
我遇到了很奇怪的事情,我不明白为什么会发生。 我做这个枚举:
[Flags]
public enum EnumMoveCommand
{
None = 0x0,
Up = 0x1,
Right = 0x2,
Bottom = 0x4,
Left = 0x8,
LeftClick = 0x16,
RightClick = 0x32,
Vertical = Up | Bottom,
Horizontal = Left | Right,
Move = Up | Right | Left | Bottom
}
所以我可以这样使用它:
if ((commands & EnumMoveCommand.Left) != EnumMoveCommand.None)
{
MoveToDo.X -= this.speed.X * (float)gameTime.ElapsedGameTime.TotalSeconds;
}
if ((commands & EnumMoveCommand.Right) != EnumMoveCommand.None)
{
MoveToDo.X += this.speed.X * (float)gameTime.ElapsedGameTime.TotalSeconds;
}
if ((commands & EnumMoveCommand.Up) != EnumMoveCommand.None)
{
MoveToDo.Y -= this.speed.Y * (float)gameTime.ElapsedGameTime.TotalSeconds;
}
if ((commands & EnumMoveCommand.Bottom) != EnumMoveCommand.None)
{
MoveToDo.Y += this.speed.Y * (float)gameTime.ElapsedGameTime.TotalSeconds;
}
if ((commands & EnumMoveCommand.Horizontal) != EnumMoveCommand.None && (commands & EnumMoveCommand.Vertical) != EnumMoveCommand.None)
{
MoveToDo.X = (float)(Math.Cos(45) * MoveToDo.X);
MoveToDo.Y = (float)(Math.Sin(45) * MoveToDo.Y);
}
但是,值为0x32的RightClick不起作用,例如:
((EnumMoveCommand.RightClick & EnumMoveCommand.Right) != EnumMoveCommand.None)=true
0x32&0x2!= 0x0如何?
谢谢
Okei,所以它是十六进制而不是dec,现在这是我的代码可以工作:
None = 0x0,
Up = 0x1,
Right = 0x2,
Bottom = 0x4,
Left = 0x8,
LeftClick = 0x10,
RightClick = 0x20,
Vertical = Up | Bottom,
Horizontal = Left | Right,
Move = Up | Right | Left | Bottom
谢谢大家
[Flags]
public enum EnumMoveCommand
{
None = 0,
Up = 1<<0, //1
Right = 1<<1, //2
Bottom = 1<<2, //4
Left = 1<<3, //8
LeftClick = 1<<4, //16
RightClick = 1<<5, //32
Vertical = Up | Bottom,
Horizontal = Left | Right,
Move = Up | Right | Left | Bottom
}
更好,谢谢卡尔滕
EnumMoveCommand.RightClick
= 0x32
= 110010
EnumMoveCommand.Right
= 0x2
= 000010
110010
& 000010
= 000010
因此(((EnumMoveCommand.RightClick&EnumMoveCommand.Right)!= EnumMoveCommand.None)== true
如果要避免枚举值之间的冲突,可以使用<<
运算符。
[Flags]
public enum EnumMoveCommand
{
None = 0,
Up = 1<<0, //1
Right = 1<<1, //2
Bottom = 1<<2, //4
Left = 1<<3, //8
LeftClick = 1<<4, //16
RightClick = 1<<5, //32
Vertical = Up | Bottom,
Horizontal = Left | Right,
Move = Up | Right | Left | Bottom
}
顺便说一下,您可以使用HasFlag
函数,例如:
commands.HasFlag(EnumMoveCommand.RightClick)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.