- ·上一篇内容:C#的简单类型
- ·下一篇内容:C# 操作符优先级表(从高到低)
checked与unchecked操作符
checked(已检验)——用于设置溢出检验上下文(overflow-checking context),控制对整型算术表达式中的操作和转换进行溢出检验,在出现溢出时会抛出异常。格式为:checked(表达式)或checked{语句块}。
unchecked(未检验)——用于设置溢出检验上下文(overflow-checking context),控制对整型算术表达式中的操作和转换不进行溢出检验,在出现溢出时不抛出异常,结果为截断后的整数。格式为:unchecked(表达式)或unchecked{语句块}。
例如:
class Test {
static readonly int x = 1000000;
static readonly int y = 1000000;
static int F() {
return checked(x * y); // Throws OverflowException
}
static int G() {
return unchecked(x * y); // Returns -727379968
}
static int H() {
return x * y; // Depends on default
}
}
又例如:
try {
int i, i2 = int.MaxValue, i2 = 200;
i = checked(i1 * i2);
} catch(Exception e){
//MessageBox.Show(e.ToString());
Console.WriteLine(e.ToString());
}
本文源自:翔宇亭——IT乐园(http://www.biye5u.com),转载请保留此信息!
微信搜索“优雅的代码”关注本站的公众号,或直接使用微信扫描下面二维码关注本站公众号,以获取最新内容。
个人成长离不开各位的关注,你的关注就是我继续前行的动力。