gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 15:56:22 26 4
gpt4 key购买 nike

在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com