【问题标题】:What happens if my C# switch expression is non-exhaustive?如果我的 C# switch 表达式不是详尽的会发生什么?
【发布时间】:2019-09-27 19:15:43
【问题描述】:

在 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
        };
    }

【问题讨论】:

    标签: c# c#-8.0 switch-expression


    【解决方案1】:

    如果switch 表达式不详尽,编译器会产生警告。 在运行时,如果您传递未处理的值,则会抛出 SwitchExpressionException

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

    如果证明(使用那些 技术)某些可能的输入值可能与某些不匹配 switch_expression_arm 在运行时。

    在运行时,switch_expression 的结果是 表达式的第一个 switch_expression_arm 的表达式 switch_expression 左侧的匹配 switch_expression_arm 的模式,而 case_guard 的 switch_expression_arm,如果存在,评估为真。

    如果没有 这样的 switch_expression_arm,switch_expression 会抛出一个实例 例外的 System.Runtime.CompilerServices.SwitchExpressionException。

    【讨论】:

    • 使用默认或 '_' 选项总是可以使他们的 switch 表达式详尽无遗。
    【解决方案2】:

    视情况而定。

    如果有匹配:匹配,一切都很好。

    如果没有匹配:SwitchExpressionException 被抛出。

    最佳实践似乎是编写详尽的开关表达式。如果你不这样做,并且没有爆炸,你可能只是走运了。

    如果你的 switch 表达式不详尽,编译器会警告你,但这不是错误,它会编译并运行。

    (刚刚遇到这个,所以我想分享一下 - 虽然 C# 8 仍处于预览阶段,但它还没有出现在文档中)

    【讨论】:

      【解决方案3】:

      要删除此警告,请添加默认表达式。

         exception switch
          {
              ValidationException vExp => new ValidationErrorDetail
              {
                  
              },
              ApiException apiExp => new ApiErrorDetail
              {
                 
              },
              ProcessException pExp => new ErrorDetail
              {
                 
              },
              _ => new ErrorDetail
              {
      
              }
          };
      

      添加_ =>和要执行的默认表达式。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-10
        • 2017-06-11
        • 2011-05-16
        • 2020-03-26
        • 1970-01-01
        • 2019-02-04
        相关资源
        最近更新 更多