我正在学习 C# (10.0/.NET6),我有一个问题。 有一段代码:
Int32 x = Int32.MaxValue;
Int32 y = Int32.MaxValue;
try
{
WriteLine($"{x} * {y} = {SomeFuncSwitch(x, y, 2)}");
WriteLine($"{x} + {y} = {SomeFunc(x, y)}");
}
catch ( OverflowException ex )
{
WriteLine( $"Overflow in {ex.TargetSite}!" );
}
static Int32 SomeFunc(Int32 x, Int32 y) => checked (x + y);
static Int32 SomeFuncSwitch(Int32 x, Int32 y, UInt16 condition) =>
checked (
condition switch
{
1 => x + y,
_ => x * y
}
);
SomeFunc()
抛出异常,而 SomeFuncSwitch()
则不会。如果每个 switch case 都被检查
,它就会发生。有没有(正确的)方法来使用单个checked
?
最佳答案
这似乎是使用 checked
表达式与 switch 表达式的结果。
如果你这样做(通过 checked
block ),它会按预期工作:
static Int32 SomeFuncSwitch(Int32 x, Int32 y, UInt16 condition)
{
checked
{
return condition switch
{
1 => x + y,
_ => x * y
};
}
}
和您一样,我也希望原始代码能够工作。代码生成方式可能存在一些错误。
它看起来确实像是一个编译器错误。如果你看the decompiled C# code您可以看到 SomeFuncSwitch()
中缺少 checked
表达式,但 SomeFunc()
中并未缺少该表达式。
关于C#:如何声明一个已检查的 switch-expression-bodyed 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72599991/