【问题标题】:An elegant way to get a boolean to represent 1 and -1一种获得布尔值来表示 1 和 -1 的优雅方法
【发布时间】:2014-06-13 15:07:21
【问题描述】:

这是我的一段代码,它会从左到右移动 Play Field,每次碰到边时都会向下移动一个。

    private void moveMonsterPlayField()
    {
        if (monsterPlayField.DirectionRight)
        {
            monsterPlayField.X++;
            if (monsterPlayField.X + monsterPlayField.Width >= this.width)
            {
                monsterPlayField.DirectionRight = false;
                monsterPlayField.Y++;
            }
        }

        else 
        {
            monsterPlayField.X--;
            if (monsterPlayField.X == 0)
            {
                monsterPlayField.DirectionRight = true;
                monsterPlayField.Y++;
            }
        }



    }

但是有点冗长。

相反,我想做这样的事情:

    private void moveMonsterPlayField()
    {
       monsterPlayField.X += monsterPlayField.DirectionRight * 1 //where DirectionRight resolves to 1 or -1

       if (monsterPlayField.X + monsterPlayField.Width >= this.width || monsterPlayField.X == 0)
       {
           monsterPlayField.DirectionRight = !monsterPlayField.DirectionRight;
           monsterPlayField.Y++;
       }



    }

这可能吗?

【问题讨论】:

    标签: c# boolean


    【解决方案1】:

    你可以这样使用:

    monsterPlayField.X += monsterPlayField.DirectionRight ? 1 : -1;
    

    其实这只是一个if 语句,有truefalse 结果。

    其他选项:

    • 您可以在您的类中添加另一个属性来计算它。
    • 创建一个类,并将转换运算符重写为 boolint,尽管我个人会远离这个。

    【讨论】:

    • 这正是我想要的。谢谢。 :)
    【解决方案2】:

    您可能考虑的另一种选择是使用两个整数属性来表示怪物的当前速度,指定 X 和 Y 分量:

    int VelocityX;
    int VelocityY;
    

    目前您会将这些值限制为 -1、0 和 1(但您可以在未来指定更高的速度)。

    那么你调整怪物 (X,Y) 位置的代码是:

    monsterPlayField.X += monsterPlayField.VelocityX;
    monsterPlayField.Y += monsterPlayField.VelocityY;
    

    您仍然需要在更改 X 和 Y 值后对其进行范围检查。

    【讨论】:

    • 我已经勾选了这个答案,对于给定的代码,这个解决方案更合适。
    【解决方案3】:

    另一种选择是使用枚举并将值分配给枚举成员。

    enum Direction
    {
        Right = 1,
        Left = -1
    }
    

    然后,您可以在代码中将枚举转换为它们的 int 值。

    private void moveMonsterPlayField()
    {
       monsterPlayField.X += (int)monsterPlayField.Direction; // Direction is now of type Direction instead of bool
    
       if (monsterPlayField.X + monsterPlayField.Width >= this.width || monsterPlayField.X == 0)
       {
           monsterPlayField.Direction = (Direction)((int)monsterPlayField.Direction * -1); 
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多