1 c# enums if-statement unity-game-engine
我在编写新的 Unity 项目时偶然发现了这个问题。我仍在学习有关 C# 的某些知识,但据我了解,以下错误应该是不可能的。如果事实上我错了并且对此有一个明显的解释,我会很高兴了解它。
重要的代码位如下:
公众声明enum
:
public enum RoadDirection
{
Up,
Down,
Left,
Right
}
Run Code Online (Sandbox Code Playgroud)
调用该函数以从以下位置选择一个随机值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;
}
}
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)
这些是我的脚本中唯一与该函数相关/使用该函数的部分。else
即使已经涵盖了所有可能性,是否有理由触发这些事件?
我添加了else
- 语句来调试是否这是发生错误的地方,它else
已经修复,但其背后的原因仍然很有趣。
问题是您GetRoadDirection
在每种if
情况下都调用该方法。由于该方法每次返回一个随机值,因此任何条件为真的可能性只有 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
}
Run Code Online (Sandbox Code Playgroud)
在不显式捕获值的情况下执行此操作的一种方法是使用语句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;
}
Run Code Online (Sandbox Code Playgroud)
作为旁注,您可以将 an 转换int
为 an enum
,因此您的GetRoadDirection
方法可以简化为:
RoadDirection GetRoadDirection()
{
return (RoadDirection) Random.Range(0, 4);
}
Run Code Online (Sandbox Code Playgroud)