c# checked unchecked 关键字
checked 和 unchecked关键字用来限定检查或者不检查数学运算溢出的;如果使用了checked发生数学运算溢出时会抛出OverflowException;如果使用了unchecked则不会检查溢出,算错了也不会报错。
1. 一段编译没通过的代码
1
|
int a = int .MaxValue * 2; |
以上代码段编译没有通过,在VS2010中会有一条红色的波浪线指出这段代码有问题:”The operation overflows at compile time in checked mode”。这说明了编译器会在编译时检查数学运算是否溢出。但是编译时能检查出溢出的情况仅限于使用常量的运算。2中的代码编译器就不报不出错误来了。
2. 一段编译通过但是不能得到正确结果的代码
1
2
3
|
int temp = int .MaxValue; int a = temp * 2; Console.Write(a); |
我先把常量int.MaxValue的值给了临时变量temp,然后使用临时变量乘以2计算结果赋值给a;这段代码是可以正常执行的,执行结果将输出 -2。
这说明在运行时默认情况程序是不会检查算术运算是否溢出的,cpu只管算,对于它来讲按规则算就是了,结果对不对不是他的错。
正常执行了,而结果是错误的,这是非常危险的情况,该如何避免这种危险呢?请看3
3. 使用checked关键字,溢出时报警
1
2
3
4
5
6
7
8
9
10
|
int temp = int .MaxValue; try { int a = checked (temp * 2); Console.WriteLine(a); } catch (OverflowException) { Console.WriteLine( "溢出了,要处理哟" ); } |
使用checked关键字修饰temp*2的计算结果,并使用try catch在发生溢出时做处理。以上代码将输出:“溢出了,要处理哟”
问题是如果一段代码中有很多算术运算都需要做溢出检查,那会有很多checked修饰的表达式,怎么办呢?请看4
4. checked关键字可以修饰一个语句块,请看下面代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
int temp = int .MaxValue; try { checked { int num = temp / 20; int a = temp * 2; int c = temp * 1000; } } catch (OverflowException) { Console.WriteLine( "溢出了,要处理哟" ); } |
以上程序输出结果和3一样
5. checked在避免算术溢出方面很有用,那么unchecked呢,它有用吗?答案是肯定的,有时候我们不需要准确的计算结果,我们只是需要那么一个数而已,至于溢出不溢出的关系不大,比如说生成一个对象的HashCode,比如说根据一个算法计算出一个相对随机数,这都是不需要准确结果的。如下代码片段
1
2
3
4
5
6
7
8
9
10
11
12
|
class Person { public string Name { get ; set ; } public string Title { get ; set ; } public override int GetHashCode() { return unchecked (Name.GetHashCode() + Title.GetHashCode()); } } |
unchecked也可以修饰语句块,其用法和checked完全一样。
6. checked和unchecked是可以嵌套使用的,虽然没啥意义。语句是否是checked以最近嵌套的checked或者unchecked决定
7. 从IL中看checked关键字
C#代码:
static void Main( string [] args) { int a = int .MaxValue; int b = a * 2; int c = checked (a * 2); int d = unchecked (a + 3); Console.Read(); } |
对应IL
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 26 (0x1a)
.maxstack 2
.locals init ([0] int32 a,
[1] int32 b,
[2] int32 c,
[3] int32 d)
IL_0000: nop
IL_0001: ldc.i4 0x7fffffff
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldc.i4.2
IL_0009: mul
IL_000a: stloc.1
IL_000b: ldloc.0
IL_000c: ldc.i4.2
IL_000d: mul.ovf
IL_000e: stloc.2
IL_000f: ldloc.0
IL_0010: ldc.i4.3
IL_0011: add
IL_0012: stloc.3
IL_0013: call int32 [mscorlib]System.Console::Read()
IL_0018: pop
IL_0019: ret
} // end of method Program::Main
请看IL中的红色和绿色加重显示代码,可以看出使用checked时,IL的运算是mul.ovf;不使用checked或者使用unchecked时的IL运算函数是mul或者add,不带.ovf。
8. checked或者unchecked只影响其包围的语句,不会影响到包围的语句内调用函数的代码块,如下示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
static void Main( string [] args) { int a = int .MaxValue; int b = 20; checked { int c = TestMethod(a, b); Console.WriteLine(c); } } static int TestMethod( int a, int b) { return a * b; } |
上面代码将会正常执行,checked语句块并未起到应有的作用。
9. 全局开启或者关闭checked编译选项
在项目属性页上选择“生成”选项卡,然后点击“高级”按钮,选中“检查数学运算溢出”选项,如下示意图
总结:
checked和unchecked是两个不常用的关键字,但是他们俩是有用的,在需要的时候请记得用他们两位,另外建议测试时开启全局checked编译器选项,谢谢。
c# checked unchecked 关键字的更多相关文章
- C# checked和unchecked 关键字详解
checked 和 unchecked关键字用来限定检查或者不检查数学运算溢出的:如果使用了checked发生数学运算溢出时会抛出OverflowException:如果使用了unchecked则不会 ...
- Checked&Unchecked Exception
Java 中定义了两类异常: 1) Checked exception: 这类异常都是Exception的子类 .异常的向上抛出机制进行处理,如果子类可能产生A异常,那么在父类中也必须throws A ...
- throws ? catch checked unchecked
ThrowableClass Error (unchecked) Exception IOException (checked) RuntimeException (unchecked) publi ...
- checked,unchecked
static void Main(string[] args) { byte b1 = 100; byte b2 = 250; //Checked try { byte sum = checked ( ...
- C# yield checked,unchecked lock语句(C#学习笔记04)
特殊语句 yield语句 yield用于终止迭代 只能使用在返回类型必须为 IEnumerable.IEnumerable<T>.IEnumerator 或 IEnumerator< ...
- C# checked unchecked
static void CheckedUnCheckedDemo() { int i = int.MaxValue; try { //checked //{ // Console.WriteLine( ...
- c# unchecked关键字。byte 合并short
参考MSDN 代码: public class BytesOperate { /// <summary> /// 计算校验和,SUM /// </summary> public ...
- C#的checked和unchecked
C#的 checked关键字用于对整型算术运算和转换显式启用溢出检查. 简单点说,我们在进行数值计算时,运算结果可能会超出该类型能表达的数值范围,因而结果溢出.而这个溢出如果是含有变量的表达式的话,编 ...
- C# checked和unchecked详解
1.对基元类型执行的许多算术运算都可能造成溢出,有如下代码: Byte b=100; b=(Byte)(b+200); 简单的解读上面的代码: 第一步,将所有的操作数都扩大至32位或者64位(根据操作 ...
随机推荐
- 【128】Word中的VBA
通过查找关键字,然后删除整段文字的实现! Sub 删除查找含关键词的行() Dim KeyWord As String KeyWord = InputBox("请输入关键词(词长不限,中英均 ...
- 安装完Oracle之后的注意事项
1.修改密码过期问题.ALTER PROFILE DEFAULT LIMIT PASSWORD_LIFE_TIME UNLIMITED; 2.修改最大连接数问题. alter system set p ...
- SFTPTool 和 FTPTooL.java
两个工具类依赖的jar包: FTPTool.java public static void main(String[] args) throws Exception{ FTPTooL ftpTool ...
- poj 2594 Treasure Exploration(最小路径覆盖+闭包传递)
http://poj.org/problem?id=2594 Treasure Exploration Time Limit: 6000MS Memory Limit: 65536K Total ...
- 一键安装GitLab7
1. Install and configure the necessary dependencies If you install Postfix to send email please sele ...
- 随笔2 PAT1001.A+B Format (20)
1001.A+B Format(20) 题目链接 1001.A+B Format (20) C++ 代码 第一次使用markdown,还不是很习惯,现在努力的在适应它 首先这道题我们很容易就可以读懂题 ...
- HDU2948Geometry Darts(简单计算几何)
题目大意就是说两个人掷飞镖,飞镖在所给定的图形内就记一分,现在给定N个图形(圆.三角形和矩形),问每一次比赛(没人分别掷三次)谁赢. #include <map> #include < ...
- CSS line-height 和 vertical-align 精解(下篇)
申明本文转自:http://hi.baidu.com/wolongxzg/item/2383860ec8ac8b173a53eeb0 vertical-align 7.4.1 语法 vertical- ...
- android Intent的startActivityForResult()方法
startActivityForResult() 之前学习了利用Intent跳转页面的同时传值,但有的时候需要从跳转到的页面返回所需要的值(如修改了用户信息,需要返回修改的信息),通俗的意思就是A.A ...
- C#调用webService的几种方法
转自: WebClient 用法小结 http://www.cnblogs.com/hfliyi/archive/2012/08/21/2649892.html http://www.cnblogs. ...