gpt4 book ai didi

c# - C#检查表达式的动态 "Scoping"

转载 作者:太空狗 更新时间:2023-10-30 00:15:00 24 4
gpt4 key购买 nike

是否有可能(在 C# 中)使 checked(...) 表达式具有用于溢出检查的动态“作用域”?换句话说,在下面的例子中:

int add(int a, int b)
{
return a + b;
}
void test()
{
int max = int.MaxValue;
int with_call = checked(add(max, 1)); // does NOT cause OverflowException
int without_call = checked(max + 1); // DOES cause OverflowException
}

因为在表达式checked(add(max, 1))中,一个函数调用导致溢出,没有抛出OverflowException,即使在 checked(...) 表达式的dynamic 范围内发生溢出。

有什么方法可以使两种计算int.MaxValue + 1的方法都抛出OverflowException吗?

编辑:好吧,要么告诉我是否有办法,要么给我一个更好的方法(请)。

我认为我需要这个的原因是因为我有这样的代码:

void do_op(int a, int b, Action<int, int> forSmallInts, Action<long, long> forBigInts)
{
try
{
checked(forSmallInts(a, b));
}
catch (OverflowException)
{
forBigInts((long)a, (long)b);
}
}
...
do_op(n1, n2,
(int a, int b) => Console.WriteLine("int: " + (a + b)),
(long a, long b) => Console.WriteLine("long: " + (a + b)));

如果 a + bint 范围内,并且 long,我希望它打印 int: ...: ... 如果小整数加法溢出。有没有比简单地更改每个 Action(我有很多)更好的方法?

最佳答案

简而言之,检查 block 或表达式不可能具有动态范围。如果你想在整个代码库中应用它,你应该考虑将它添加到你的 compiler options 中。 .

应在操作实际发生的地方使用已检查的表达式或已检查的 block 。

    int add(int a, int b)
{
int returnValue = 0;

try
{
returnValue = checked(a + b);
}
catch(System.OverflowException ex)
{
//TODO: Do something with exception or rethrow
}

return returnValue;
}

void test()
{
int max = int.MaxValue;
int with_call = add(max, 1);
}

关于c# - C#检查表达式的动态 "Scoping",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18243456/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com