unity3d 不应到达的Else语句

2admgd59  于 2023-04-12  发布在  其他
关注(0)|答案(1)|浏览(148)

我在编写一个新的Unity项目时偶然发现了这个问题。我仍然在学习C#的某些知识,但据我所知,下面的错误不应该是可能的。如果事实上我错了,并且有一个明显的解释,我很乐意学习它。
重要的代码位如下:
public enum的声明:

public enum RoadDirection
{
    Up,
    Down,
    Left,
    Right
}

调用该函数从enum中选择一个随机值:

RoadDirection GetRoadDirection()
{
    int randomDir = Random.Range(0, 4);
    switch (randomDir)
    {
        case 0:
            return RoadDirection.Up;
        case 1:
            return RoadDirection.Down;
        case 2:
            return RoadDirection.Right;
        case 3:
            return RoadDirection.Left;
        default:
            return RoadDirection.Up;
    }
}

if-语句使用以下函数:

if (GetRoadDirection() == RoadDirection.Up)
{
    // does stuff
}
else if (GetRoadDirection() == RoadDirection.Down)
{
    // does stuff
}
else if (GetRoadDirection() == RoadDirection.Left)
{
    // does stuff
}
else if (GetRoadDirection() == RoadDirection.Right)
{
    // does stuff
}
else
{
    // shouldn't even happen but does stuff
}

这些是我的脚本中唯一相关/使用该函数的部分。即使已经涵盖了所有可能性,为什么else会被触发?
我添加了else-语句来调试是否这是错误发生的地方,对于else,它已经被修复了,但它背后的原因仍然很有趣。

vatpfxk5

vatpfxk51#

问题是,在每个if条件中调用GetRoadDirection方法。由于该方法每次返回一个随机值,因此任何条件都只有25%的机会为真。相反,您应该捕获一次值并存储它,然后进行评估:

var direction = GetRoadDirection();

if (direction == RoadDirection.Up)
{
    // does stuff
}
else if (direction == RoadDirection.Down)
{
    // does stuff
}
else if (direction == RoadDirection.Right)
{
    // does stuff
}
else if (direction == RoadDirection.Left)
{
    // does stuff
}
else
{
    // shouldn't ever happen
}

一种不显式捕获值的方法是使用switch语句(switch将在内部捕获值):

switch (GetRoadDirection())
{
    case RoadDirection.Up:
        // does stuff
        break;
    case RoadDirection.Down:
        // does stuff
        break;
    case RoadDirection.Right:
        // does stuff
        break;
    case RoadDirection.Left:
        // does stuff
        break;
    default:
        // shouldn't ever happen
        break;
}

顺便说一下,你可以将int转换为enum,所以你的GetRoadDirection方法可以简化为:

RoadDirection GetRoadDirection()
{
    return (RoadDirection) Random.Range(0, 4);
}

相关问题