Checked与Unchecked     
          
     对于因为整数类型参与算术操作和类型转换时产生的“溢出异常”——System.OverflowException,在某些算法来讲不算真正的“异常”,相反这种溢出常常为程序所用。C#通过引入checked和unchecked关键字来控制这种特殊情况的需求。它们都可以加于一个语句块前(如:checked{……}),或者一个算术表达式前(如:unchecked(x+y)),其中加checked标志的语句或表达式如果发生算术溢出,则抛出System.OverflowException类型的异常,而加unchecked标志的语句发生算术溢出时,则不抛出异常。下面是一个示例:     
          
  using    System;     
          
     
class    Test{     
          
     
static    void    Main()    {     
          
     
int    num1=100000,num2=100000,     
          
     result
=0;     
          
     
checked{    try    {    result=    num1    *    num2;}     
          
     
catch(System.Overflo2wException    e){    Console.WriteLine(e);    }     
          
     
finally{    Console.WriteLine(result);}     
          
     }     
          
     
unchecked{    try    {    result=    num1    *    num2;}     
          
     
catch(System.OverflowException    (e){    Console.WriteLine(e);}     
          
     
finally{    Console.WriteLine(result);}     
          
     }     
          
     }     
          
     }  
   
          
     程序输出:     
          
     System.OverflowException:    Arithmetic    operation    resulted    in    an    overflow.     
          
     at    Test.Main()     
          
     0     
          
     1410065408     
          
     可以看到同样的算术操作,用checked抛出了溢出异常,而unchecked只是将溢出的位丢弃而得到剩下的32位组成的十进制整数值。值得指出的是可以用“/checked”编译器选项指定整个文件的代码为checked语义,如果没有指定则默认为unchecked。如果同时在程序代码中指定checked或unchecked标志,又有了checked编译器选项,则除了标志为unchecked的代码外,其余的都有checked语义。
posted on 2009-08-31 22:37  钱途无梁  阅读(1458)  评论(0编辑  收藏  举报