我正在學習 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
?
uj5u.com熱心網友回復:
這似乎是使用checked
帶有 switch 運算式的運算式的結果。
如果你這樣做(通過一個checked
塊),它會按預期作業:
static Int32 SomeFuncSwitch(Int32 x, Int32 y, UInt16 condition)
{
checked
{
return condition switch
{
1 => x y,
_ => x * y
};
}
}
像你一樣,我希望原始代碼能夠作業。代碼生成方式可能存在一些錯誤。
它肯定看起來像一個編譯器錯誤。如果您查看反編譯的 C# 代碼,您會發現該checked
運算式SomeFuncSwitch()
在SomeFunc()
.
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/490999.html
上一篇:當我在ControllerAdvice中有RuntimeException的ExceptionHandler時,不會呼叫springAccessDeniedHandler介面?