c# - 如果我的 C# switch 表达式不是详尽的,会发生什么?

标签 c# c#-8.0 switch-expression

在 C# 8 中,引入了 switch 表达式。如果 switch 表达式不是详尽的,会发生什么?换句话说,如果我不测试每个可能的值会发生什么?

    static void Main(string[] args)
    {
        int x = 1;
        int imExhaustive = x switch
        {
            3 => 4,
            _ => 0   // x = 1 matches this
        };
        int okFine = x switch
        {
            1 => 4   // x = 1 matches this
        };
        int noMatch = x switch
        {
            3 => 4   // No match
        };
    }

最佳答案

如果switch表达式并非详尽无遗,编译器会产生警告。
在运行时,如果你传递一个未被处理的值,一个 SwitchExpressionException被抛出。

这在 C# 8.0 中新模式特性的 speclet 中有记录:https://github.com/dotnet/csharplang/blob/master/proposals/csharp-8.0/patterns.md#switch-expression

The compiler shall produce a warning if it proves (using those techniques) that some possible input value might not match some switch_expression_arm at runtime.

At runtime, the result of the switch_expression is the value of the expression of the first switch_expression_arm for which the expression on the left-hand-side of the switch_expression matches the switch_expression_arm's pattern, and for which the case_guard of the switch_expression_arm, if present, evaluates to true.

If there is no such switch_expression_arm, the switch_expression throws an instance of the exception System.Runtime.CompilerServices.SwitchExpressionException.

关于c# - 如果我的 C# switch 表达式不是详尽的,会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56068105/

相关文章:

c# - EF 6,从数据库更新模型不支持对象上下文?

c# - 想学习编写 2d 游戏

async-await - Resharper 建议将 Using 语句转换为单个 "await Using"?

c# - 为什么 IAsyncEnumerator 在 C#8 中没有 Reset 方法?

c# - 如何为整个项目启用 C# 8.0 的 Nullable Reference Types 功能

c# - LINQ Sum 嵌套集合与 GroupBy 和 OrderByDescending

c# - IIS 应用程序上的 ProtectedData.Unprotect - 在 IISRESET 后无法工作

java - 为什么 Switch 需要语句但接受表达式

java - 从 Java-12 中的 switch 表达式返回通用值