本文以实例形式对比测试了c#中checked和unchecked的区别,对于c#初学者来说有很好的借鉴参考价值。具体分析如下:
int类型的最大值是2147483647,2个最大值相加就会超出int的最大值,即出现溢出。
class program { static void main(string[] args) { int y = 2147483647; int x = 2147483647; int z = x + y; console.writeline(z.tostring()); console.readkey(); } }
把断点打在 int z = x + y;代码行,单步调试,可以看到z的值为-2。因为int类型的最大值是2147483647,x + y超出了最大值,出现了溢出。
程序运行效果如下图所示:
一、使用checked:
如果我们想让编译器帮我们判断是否溢出,就使用checked关键字。
class program { static void main(string[] args) { int y = 2147483647; int x = 2147483647; int z = checked(x + y); } }
运行后抛出溢出异常,运行结果如下图所示:
如果我们想手动捕获并打印异常,应该这样写:
class program { static void main(string[] args) { int y = 2147483647; int x = 2147483647; try { int z = checked(x + y); } catch (overflowexception ex) { console.writeline(ex.message); } console.readkey(); } }
运行结果如下图所示:
二、使用unchecked:
使用unchecked不会抛出溢出异常。
class program { static void main(string[] args) { int y = 2147483647; int x = 2147483647; int z = unchecked(x + y); console.writeline(z.tostring()); console.readkey(); } }
结果为:-2
如对本文有疑问, 点击进行留言回复!!
使用Visual Studio2019创建C#项目(窗体应用程序、控制台应用程序、Web应用程序)
C#实现获取本地内网(局域网)和外网(公网)IP地址的方法分析
网友评论