C#:如何声明一个已检查的 switch-expression-bodyed 函数?

标签 c# exception switch-statement checked expression-body

我正在学习 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/

相关文章:

c++ - 错误 C2361 : initialization of 'found' is skipped by 'default' label

c# - C#中switch语句的多个变量

java - 在 Android 应用程序的导航菜单内创建一个警报对话框以注销

c# - 具有子属性的依赖属性更新主属性?

c# - 如何使用 LINQ 计算 DataTable 的总和?

java - 如何在我的程序中使用 try/catch/finally 过滤扫描仪输入错误?

c# - 无法加载文件或程序集 stdole

android - 解析 XML 时出错 : unbound prefix on custom LinearLayout

c# - 水平对齐包裹面板中的子元素

c# - WPF Datagrid 不显示所有值