[英]C#: How to declare a checked switch-expression-bodied function?
我正在研究 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
,它就会。 有没有(正确的)方法来使用 single checked
?
这似乎是使用带有 switch 表达式的已checked
表达式的结果。
如果你这样做(通过checked
块),它会按预期工作:
static Int32 SomeFuncSwitch(Int32 x, Int32 y, UInt16 condition)
{
checked
{
return condition switch
{
1 => x + y,
_ => x * y
};
}
}
像你一样,我希望原始代码能够工作。 代码的生成方式可能存在一些错误。
它看起来确实像一个编译器错误。 如果您查看反编译的 C# 代码,您会发现 SomeFuncSwitch() 中缺少已checked
的表达式,但SomeFunc()
SomeFuncSwitch()
中并未缺少。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.