您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

C# checked与unchecked用法

2026/1/23 7:50:56发布15次查看
checked 关键字用于对整型算术运算和转换显式启用溢出检查。
默认情况下,如果表达式仅包含常数值,且产生的值在目标类型范围之外,则它会导致编译器错误。 如果表达式包含一个或多个非常数值,则编译器不检测溢出。 在下面的示例中,计算赋给 i2 的表达式不会导致编译器错误。
// the following example causes compiler error cs0220 because 2147483647 // is the maximum value for integers. //int i1 = 2147483647 + 10; // the following example, which includes variable ten, does not cause // a compiler error. int ten = 10; int i2 = 2147483647 + ten; // by default, the overflow in the previous statement also does // not cause a run-time exception. the following line displays // -2,147,483,639 as the sum of 2,147,483,647 and 10. console.writeline(i2);
默认情况下,在运行时也不检查这些非常数表达式是否溢出,这些表达式不引发溢出异常。上面的示例显示 -2,147,483,639 作为两个正整数之和。
可以通过编译器选项、环境配置或使用 checked 关键字来启用溢出检查。 下面的示例演示如何使用 checked 表达式或 checked 块,在运行时检测由前面的求和计算导致的溢出。 两个示例都引发溢出异常。
// if the previous sum is attempted in a checked environment, an // overflowexception error is raised. // checked expression. console.writeline(checked(2147483647 + ten)); // checked block. checked { int i3 = 2147483647 + ten; console.writeline(i3); }
可以使用unchecked取消溢出检查
此示例演示如何使用 checked 启用运行时溢出检查。
class overflowtest { // set maxintvalue to the maximum value for integers. static int maxintvalue = 2147483647; // using a checked expression. static int checkedmethod() { int z = 0; try { // the following line raises an exception because it is checked. z = checked(maxintvalue + 10); } catch (system.overflowexception e) { // the following line displays information about the error. console.writeline("checked and caught: " + e.tostring()); } // the value of z is still 0. return z; } // using an unchecked expression. static int uncheckedmethod() { int z = 0; try { // the following calculation is unchecked and will not // raise an exception. z = maxintvalue + 10; } catch (system.overflowexception e) { // the following line will not be executed. console.writeline("unchecked and caught: " + e.tostring()); } // because of the undetected overflow, the sum of 2147483647 + 10 is // returned as -2147483639. return z; } static void main() { console.writeline("\nchecked output value is: {0}", checkedmethod()); console.writeline("unchecked output value is: {0}", uncheckedmethod()); } /* output: checked and caught: system.overflowexception: arithmetic operation resulted in an overflow. at consoleapplication1.overflowtest.checkedmethod() checked output value is: 0 unchecked output value is: -2147483639 */ }
以上就是c# checked与unchecked用法的内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product