C#:如何声明检查的开关表达式功能?

发布于 2025-02-06 21:21:51 字数 709 浏览 0 评论 0原文

我正在说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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

泪意 2025-02-13 21:21:51

这似乎是使用Switch表达式使用检查表达式的结果。

如果您这样做(通过检查块),它可以按预期工作:

static Int32 SomeFuncSwitch(Int32 x, Int32 y, UInt16 condition)
{
    checked
    {
        return condition switch
        {
            1 => x + y,
            _ => x * y
        };
    }
}

像您一样,我希望原始代码可以正常工作。代码的生成方式可能存在一些错误。

当然,它看起来像一个编译器错误。 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:

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().

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文