码迷,mamicode.com
首页 > Windows程序 > 详细

探讨c#中的unchecked是什么意思,起什么作用?

时间:2015-05-13 00:41:05      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:

Checked与Unchecked     
对于因为整数类型参与算术操作和类型转换时产生的“溢出异常”——System.OverflowException,在某些算法来讲不算真正的“异常”,相反这种溢出常常为程序所用。C#通过引入checked和unchecked关键字来控制这种特殊情况的需求。它们都可以加于一个语句块前(如:checked{……}),或者一个算术表达式前(如:unchecked(x+y)),其中加checked标志的语句或表达式如果发生算术溢出,则抛出System.OverflowException类型的异常,而加unchecked标志的语句发生算术溢出时,则不抛出异常。下面是一个示例:   

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    
    class Program
    {
        private delegate string GetAString();

        static void Main(string[] args)
        {
            int num1 = 100000, num2 = 100000,result = 0;
            checked
            {
                try { result = num1 * num2; }
                catch (Exception e) { Console.WriteLine(e); }
                finally { Console.WriteLine(result); }
            }
            unchecked
            {
                try { result = num1 * num2; }
                catch (System.OverflowException e) { Console.WriteLine(e); }
                finally { Console.WriteLine(result); }
            }
            try { result = num1 * num2; }
            catch (System.OverflowException e) { Console.WriteLine(e); }
            finally { Console.WriteLine(result); }
            
            Console.Read();
        }
    }
    
}

  


程序输出:     

技术分享

由此看出,默认情况下是unchecked

 

可以看到同样的算术操作,用checked抛出了溢出异常,而unchecked只是将溢出的位丢弃而得到剩下的32位组成的十进制整数值。值得指出的是可以用“/checked”编译器选项指定整个文件的代码为checked语义,如果没有指定则默认为unchecked。如果同时在程序代码中指定checked或unchecked标志,又有了checked编译器选项,则除了标志为unchecked的代码外,其余的都有checked语义。

探讨c#中的unchecked是什么意思,起什么作用?

标签:

原文地址:http://www.cnblogs.com/niaowo/p/4499008.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!