C#:如何声明检查的开关表达式功能?
我正在说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()
没有。如果每个开关案例都是检查
。是否有(适当的)使用单个检查的方法
?
I'm stuyding C# (10.0/.NET6) and I've got a question.
There is a code:
Int32 x = Int32.MaxValue;
Int32 y = Int32.MaxValue;
try
{
WriteLine(quot;{x} * {y} = {SomeFuncSwitch(x, y, 2)}");
WriteLine(quot;{x} + {y} = {SomeFunc(x, y)}");
}
catch ( OverflowException ex )
{
WriteLine( quot;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()
throws exception, whereas SomeFuncSwitch()
does not. It will if every switch case is checked
. Is there a (proper) way to use single checked
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这似乎是使用Switch表达式使用
检查
表达式的结果。如果您这样做(通过
检查
块),它可以按预期工作:像您一样,我希望原始代码可以正常工作。代码的生成方式可能存在一些错误。
当然,它看起来像一个编译器错误。 If you look at the decompiled C# code you can请参阅
检查
表达式中缺少somefuncswitch()
,但并不缺少somefunc()
。This appears to be a consequence of the use of a
checked
expression with a switch expression.If you do it like this (via a
checked
block), it works as expected:Like you, I would have expected the original code to work. Possibly there is some bug in the way the code is generated.
It certainly looks like a compiler bug. If you look at the decompiled C# code you can see that the
checked
expression is missing fromSomeFuncSwitch()
but it is not missing fromSomeFunc()
.