Unity中C# switch表达式返回时出现CS8504错误的解决求助
修复CS8504: Pattern missing错误的方法
错误根源是switch表达式的默认分支语法不符合C#规范,C#的switch表达式要求默认分支必须使用通配符_作为匹配模式,你当前代码的最后一行=> throw new Exception(...)缺少了这个通配符。
修改后的正确代码如下:
public static Vector3Int GetVector(this Direction direction) { return direction switch { Direction.up => Vector3Int.up, Direction.down => Vector3Int.down, Direction.right => Vector3Int.right, Direction.left => Vector3Int.left, Direction.forward => Vector3Int.forward, Direction.backwards => Vector3Int.back, _ => throw new Exception("Invalid direction provided.") }; }
补充说明
- 即便你的枚举已经覆盖所有方向,保留默认分支仍是良好的编程习惯,能避免后续枚举新增成员时出现未处理的异常。
- 确保你的Unity项目使用的C#版本支持switch表达式(C# 8.0及以上),Unity 2020.1及后续版本默认支持该特性,若为旧版本需在Player Settings中开启对应C#版本。
内容的提问来源于stack exchange,提问作者Bunabyte
相关产品推荐
相关产品推荐

