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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 16:05:26