带有多个选项的内联if-else语句

时间:2014-02-13 12:32:01

标签: c# if-statement unity3d inline

所以,我正在查看使用三元运算符的Inline if语句。基本上这是我目前的代码,我希望它更紧凑。

private void Move(Vector3 direction) {
    if(direction != Vector3.back && direction != Vector3.forward) 
        transform.Rotate(0,(direction == Vector3.right ? 90 : -90),0);
    else 
        transform.Rotate(0,(direction == Vector3.back ? 180 : 0),0);

    transform.Translate(Vector3.forward, Space.Self);
}

我真正想要的是像这样压缩的东西:

private void Move(Vector3 direction) {
    transform.Rotate(0,(direction == Vector3.right ? 90 : -90 || direction == Vector3.back ? 180 : 0),0);
    transform.Translate(Vector3.forward, Space.Self);
}

有没有这样做?举个例子吧。我想知道如何压缩多个内联if语句,所以如果我能避免它,我就没有必要有更多的代码行。

感谢您抽出宝贵时间阅读我的问题。

2 个答案:

答案 0 :(得分:4)

这不是你要求的,但为了使方法更紧凑,也许试试这个:

public enum Direction
{
   Left = -90,
   Right = 90,
   Forward =0,
   Back = 180
}

private void Move(Direction direction) 
{
   transform.Rotate(0,(int)direction,0);
   transform.Translate(Vector3.forward, Space.Self);
}

答案 1 :(得分:1)

我会说第一个足够紧凑。如果Vector3枚举有4个值,则第二个示例将不起作用。使它工作可能看起来和第一个例子一样长。

private void Move(Vector3 direction)
{
    transform.Rotate(0,
        direction == Vector3.right ? 90 :
            (direction == Vector3.left ? -90
                (direction == Vector3.back ? 180 : 0)), 0);
    ...
}

当您只有两个要测试的值时,三元运算最“紧凑”。

例如:

Color color;

if (title == "VIP")
    color = Color.Red;
else
    color = Color.Blue;

变为:

var color = (title == "VIP" ? Color.Red : Color.Blue);