c#美味:使用checked语句避免数据溢出
核心提示:在C#中有1个关键字checked,它用来判定当前上下文中的数值运算和数值转换是否是会溢出。如是是常量溢出,那在编译时便可以发现;假设是变量溢出,那在运行时会抛出OverflowException。
在C#中有1个关键字checked,它用来判定当前上下文中的数值运算和数值转换是否是会溢出。如是是常量溢出,那在编译时便可以发现;假设是变量溢出,那在运行时会抛出OverflowException。
数值运算有:++ — - (unary) + - * /
有了这个就不用担心数据溢出了。
checked
checked 有两种使用方法:
1.作为操纵符来使用
int a = int.MinValue; int c = checked(a--); |
履行的时候会抛出异常:
2.检查1大块代码:
这模样会对里面所有的代码都做检查
checked { int a = int.MinValue; int c = a--; } |
以下图:
unchecked
和checked对应,还有1个unchecked关键字,用来取消检查。
也是两种使用;
1.作为运算符:
int a = int.MinValue; int c = unchecked(a--); |
这模样就不会抛异常了
2.检查1大块代码
unchecked { int a = int.MinValue; int c = a--; } |
也不抛异常:
/checked 和/checked-
假设代码里总是要写这么多checked语句是否是很烦?假设能有1个编译参数就好,只有设置了就都会检查。微软也想到了这个,它提供了1个/checked 参数来做,也提供了1个/checked-来取消。
溢出检查 /checked,也能够是/checked+
溢出不检查 /checked-
固然,你想取消所有的检查也是可以的,命令行参数是/checked-
csc t2.cs /checked |
其中csc是编译器csc.exe , t2.cs 是被编译的代码文件。
我想很多人是用Visual Studio吧。VS里也是可以设置的。
步骤以下,我以VS2010为例,(VS2005,2008差未几)
1。在工程上点右键,选择菜单Properties
2。点击“Build”,再点击“Advanced”
3。在打开的对话框中,把“Check for arithmetic overflow/underflow”打上勾
几个留意
1.checked语句只对当前上下文中的代码有效,即不对调用的函数内部做检查。
static void Main(string[] args) { checked { TestFun(); } } static void TestFun() { int a = int.MinValue; int c = a--; } |
这段代码中。不会跑异常,由于checked关键字没有影响到TestFun内部。假设需要这么做的话,要末在TestFun内部加checked关键字,要末打开全局开关(加编译参数/checked或VS中设置)。
2.checked,unchecked关键字不检查左移和右移是否是溢出。
static void Main(string[] args) { checked { int a = int.MinValue; int c = a>>1; } } |
履行不会抛异常:
3.为了性能考虑,建议Debug时做检查,Release时不做检查。
参考资料
/checked (Check Integer Arithmetic)
http://msdn.microsoft.com/en-us/library/h25wtyxf(v=VS.71).aspx
Arithmetic Overflow Checking using checked/unchecked
http://www.codeproject.com/KB/cs/overflow_checking.aspx
原文地址
http://www.fw8.net/TAG:参数,代码,数值,关键字,异常
评论加载中...
|