[英]C#: How to declare a checked switch-expression-bodied function?
I'm stuyding C# (10.0/.NET6) and I've got a question.我正在研究 C# (10.0/.NET6),我有一个问题。 There is a code:
有一段代码:
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()
throws exception, whereas SomeFuncSwitch()
does not. SomeFunc()
会抛出异常,而SomeFuncSwitch()
不会。 It will if every switch case is checked
.如果每个switch case 都被
checked
,它就会。 Is there a (proper) way to use single checked
?有没有(正确的)方法来使用 single
checked
?
This appears to be a consequence of the use of a checked
expression with a switch expression.这似乎是使用带有 switch 表达式的已
checked
表达式的结果。
If you do it like this (via a checked
block), it works as expected:如果你这样做(通过
checked
块),它会按预期工作:
static Int32 SomeFuncSwitch(Int32 x, Int32 y, UInt16 condition)
{
checked
{
return condition switch
{
1 => x + y,
_ => x * y
};
}
}
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 from SomeFuncSwitch()
but it is not missing from SomeFunc()
.如果您查看反编译的 C# 代码,您会发现 SomeFuncSwitch() 中缺少已
checked
的表达式,但SomeFunc()
SomeFuncSwitch()
中并未缺少。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.