C#中使用checked和unchecked整数运算

来源:互联网 发布:mysql结构化查询语言 编辑:程序博客网 时间:2024/05/16 19:09

checked语句是以checked关键字开头的代码块,checked语句中的任何整数运算溢出都会抛出OverflowException异常,

int number = int.MaxValue;checked{    int willThrow = number++;    Console.WriteLine("永远都不会执行到这里")}

只有直接在checked块中的整数运算才会检查,例如,对于块中的方法调用,不会检查所调用的方法中的整数运算.


还可用unchecked关键字创建强制不检查溢出的代码块,unchecked块中的所有整数运算都不会检查,永远不抛出OverflowException异常

int number = int.MaxValue;unchecked{    int wontThrow = number++;    Console.WriteLine("会执行到这里")}

checked表达式用法如下:

int wontThrow = unchecked(int.MaxValue+1);// 不抛出异常int willThrow = checked(int.MaxValue+1);// 抛出异常// 复合运算符(例如+=和-=)和递增(++)递减(--)运算符都是算术运算符,都有可以用checked和unchecked关键字控制