如何检查,如果我在一个检查范围内?我在、范围内

2023-09-04 09:41:12 作者:甘愿做鱼,七秒记忆。

如何找出,使用C#code,如果我在检查上下文或没有,而不会引起/捕获的发生OverflowException ,随着性能损失招致?

How can I find out, using C# code, if I'm in a checked context or not, without causing/catching an OverflowException, with the performance penalty that incurs?

推荐答案

一个块就是检查之间的唯一区别 VS 选中是编译器为基本价值类型的算术运算产生的IL指令。换言之,存在以下之间没有可观察的区别:

The only difference between a block that is checked vs unchecked are the IL instructions generated by the compiler for basic value type arithmetic operations. In other words, there is no observable difference between the following:

checked {
  myType.CallSomeMethod();
}

myType.CallSomeMethod();

但是,可以说,有一个算术运算,如添加两个整数。您将需要得到该方法的IL指令,并检查是否在你的方法调用的指令进行检查,甚至认为还远远没有防弹。你不能告诉,如果你的自定义操作实际上是在检查块内,或者只是包围检查块,这是不是里面。

But lets say that there is an arithmetic operation, such as adding two integers. You would need to get the IL instructions for the method and check if the instructions around your method call are checked, and even that is far from bullet proof. You cannot tell if your custom operation is actually within the checked block, or just surrounded by checked blocks that it is not inside.

即使捕获异常是行不通的,因为你不能这两种情况加以区分:

Even catching an exception will not work, since you cannot differentiate between these two cases:

checked {
  int a = (Some expression that overflows);
  myType.CallSomeMethod();
}

checked {
  int a = (Some expression that overflows);
}
myType.CallSomeMethod();

这大概就是为什么十进制类型不尝试检测检查的一部分 VS 取消选中,而总是抛出发生OverflowException

This is probably part of why the Decimal type does not attempt to detect checked vs unchecked and instead always throws OverflowException.