我有Unity 2021,所以我相信它使用C#版本〉7。不知何故,我不能在Switch/Case语句中使用静态对象。
private Position getStartingPosition(Direction direction) {
switch (direction) {
case Direction Direction.EAST:
return new Position(-1, height / 2);
case Direction Direction.NORTH:
return new Position(width / 2, height);
case Direction Direction.WEST:
return new Position(width, height / 2);
case Direction Direction.SOUTH:
return new Position(width / 2, -1);
default:
throw new System.Exception("Impossible");
}
}
和方向类:
public class Direction
{
static public readonly Direction EAST = new Direction(1, 0);
static public readonly Direction NORTH = new Direction(0, -1);
static public readonly Direction WEST = new Direction(-1, 0);
static public readonly Direction SOUTH = new Direction(0, 1);
...
我得到的错误是:
Grid.cs(38,31): error CS1003: Syntax error, ':' expected
Grid.cs(38,31): error CS1513: } expected
Grid.cs(38,36): error CS1003: Syntax error, ':' expected
Grid.cs(38,36): error CS1513: } expected
Grid.cs(40,31): error CS1003: Syntax error, ':' expected
Grid.cs(40,31): error CS1513: } expected
我哪里做错了?
3条答案
按热度按时间3vpjnl9f1#
case
语句应该是var _ when direction.Equals(Class.VALUE)
,但没有声明。但是Direction
也是一个对象,因此可以使用此语句的一个选项:并使用类似以下的方法实现接口
IEquatable<Direction>
:其中
x
和y
是类中的值,用于确定两个对象是否相等。t3psigkw2#
Unity uses C# 9.0。您只能打开常量和模式(其中常量是常量模式)。
我们可以使用一个位置模式来做测试。要使用它,我们必须在类中添加一个解构器
然后我们可以这样切换:
另一个可能的模式是不需要解构器的元组模式:
另一种可能性是使用常量模式来接通
enum
常量:然后,我们向
Direction
类中添加一个如下所示的属性我让你自己初始化它,然后我们这样切换:
最后,让我们使用一个属性模式:
从C# 9.0开始,我们有了switch expression,与switch语句相比,它的语法简化了:
对于target typed new,我们可以写(以位置模式为例):
13z8s7eq3#
已经在这里得到了回答:Switch statement with static fields
我改成了