You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity项目中C#枚举判断的else分支意外触发问题咨询

问题:枚举判断意外触发else分支

问题背景

定义了包含Up、Down、Left、Right的枚举RoadDirection,通过GetRoadDirection()随机返回枚举有效值,但在多分支if-else判断时,本该被覆盖的所有枚举情况却触发了else分支。

相关代码

枚举声明

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

随机返回枚举值的函数

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-else判断

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
}

原因分析

问题的核心是每次if-else分支判断时都会调用一次GetRoadDirection(),每次调用都会生成一个新的随机枚举值。

举个实际触发else的场景:

  1. 第一个if调用函数返回Down,不满足== Up,进入下一分支;
  2. 第二个else if再次调用函数返回Left,不满足== Down,继续;
  3. 第三个else if第三次调用函数返回Right,不满足== Left,继续;
  4. 第四个else if第四次调用函数返回Up,不满足== Right;
  5. 所有分支均不匹配,最终触发else。

四次随机取值完全可能都不匹配当前分支的判断条件,这就是else被触发的根本原因。

解决方案

只调用一次GetRoadDirection(),将结果存入变量,再用这个变量完成所有分支判断:

RoadDirection currentDir = GetRoadDirection();
if (currentDir == RoadDirection.Up)
{
    // does stuff
}
else if (currentDir == RoadDirection.Down)
{
    // does stuff
}
else if (currentDir == RoadDirection.Left)
{
    // does stuff
}
else if (currentDir == RoadDirection.Right)
{
    // does stuff
}
else
{
    // 此分支几乎不会再被触发
}

也可以改用switch语句,逻辑更简洁:

RoadDirection currentDir = GetRoadDirection();
switch(currentDir)
{
    case RoadDirection.Up:
        // does stuff
        break;
    case RoadDirection.Down:
        // does stuff
        break;
    case RoadDirection.Left:
        // does stuff
        break;
    case RoadDirection.Right:
        // does stuff
        break;
    default:
        // 兜底逻辑
        break;
}

内容的提问来源于stack exchange,提问作者Kemtari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 01:20:24