2010-11-01 42 views
2

这次得到了一个很酷的位逻辑/布尔逻辑问题!按位逻辑行为(布尔逻辑)我的代码中的结构看起来不对!

我目前在使用C#作为语言的Visual Studio 2010中工作,我试图跟踪一些使用[Flags]枚举的状态。

我用他们几次(坦白地说发现他们非常有用!)

它有5个州OFC任何地方没有问题的2一切权力,名字是characterState(可变我在其中存储的值)

在下面的代码示例:

private void DebugLogState() 
{ 
    //Check and log the current state of the character 
    //If a state matches, play it's respective animation 
    if ((currentCharacterState & Controller_2D.CharacterState.Idle) > 0) 
    { 
     Debug.Log("Idle state is active, log from object: Controller_2D"); 
    } 
    if ((currentCharacterState & Controller_2D.CharacterState.Walking) > 0) 
    { 
     Debug.Log("Walking state is active, log from object: Controller_2D"); 
    } 
    if ((currentCharacterState & Controller_2D.CharacterState.Running) > 0) 
    { 
     Debug.Log("Running state is active, log from object: Controller_2D"); 
    } 
    if ((currentCharacterState & Controller_2D.CharacterState.Jumping) > 0) 
    { 
     Debug.Log("Jumping state is active, log from object: Controller_2D"); 
    } 
    if ((currentCharacterState & Controller_2D.CharacterState.Crouching) > 0) 
    { 
     Debug.Log("Crouching state is active, log from object: Controller_2D"); 
    } 
} 

现在我所希望的是比较01011(或在空闲设置为1的任何其它排列)与空闲状态(01000)&他们两个和检查> 0检查我f IDLE = true。我在我的脑海里发出了一个警报,说现在就收了!但我只是开始盯着看,想知道最好的方法是什么。

随时可以帮助我找到什么是最好的检查IDLE状态,我会尝试与我的一些旧的枚举代码在此期间比较。

回答

6

由于您使用VS2010,我假设您正在编译.NET 4.0?如果是这样,你可以使用Enum.HasFlag方法:

bool isIdleSet = currentCharacterState.HasFlag(Controller_2D.CharacterState.Idle); 

如果没有,你可以这样做:

(currentCharacterState & Controller_2D.CharacterState.Idle) == Controller_2D.CharacterState.Idle 

注意,>0方法有2个问题:

  1. 不工作正确使用值0(错误否定)。
  2. 当候选标志本身为复合状态时(错误肯定),不能正常工作。例如如果Idle1001,则1000在不应该的时候通过测试。

测试按位AND操作的结果等于候选标志本身闪避它们两个。

+0

谢谢,正是我所需要的! 而事实证明,我有我的哑巴程序到.NET 2.0 啊....这就像岩石撞在一起做饭,我知道:( 您的帮助是旅游居停了我的学习不分的Tx – Proclyon 2010-11-01 14:56:32

2

如果你对编译.NET 4.0,你可以使用Enum.HasFlags:

bool isIdle = currentCharacterState.HasFlag(Controller_2D.CharacterState.Idle); 

如果不是,您现有的逻辑是不是太遥远。我通常会做以下事情:

bool isIdle = currentCharacterState & Controller_2D.CharacterState.Idle 
    == Controller_2D.CharacterState.Idle; 
+0

谢谢大家了帮助!这是一个可行的解决方案,我无法使用.NET 4.0,但2.0版本变成了现实,所以我只能再次愚弄程序。 – Proclyon 2010-11-01 14:57:12