C#中的checked和unchecked

来源:互联网 发布:txt阅读器软件排行 编辑:程序博客网 时间:2024/06/05 02:07
 

checkedunchecked操作符用于整型算术运算时控制当前环境中的溢出检查。下列运算参与了checkedunchecked检查(操作数均为整数):

1)  预定义的++和――一元运算符。

2)  预定义的-一元运算符。

3)  预定义的+、-、×、/等二元操作符。

4)  从一种整型到另一种整型的显示数据转换。

当上述整型运算产生一个目标类型无法表示的大数时,可以有相应的处理方式:

(一)使用checked

若运算是常量表达式,则产生编译错误:The operation overflows at complie time in checked mode.

若运算是非常量表达式,则运行时会抛出一个溢出异常:OverFlowException异常

(二)使用unchecked

无论运算是否是常量表达式,都没有编译错误或是运行时异常发生,只是返回值被截掉不符合目标类型的高位。

(三)既未使用checked又未使用unchecked

若运算是常量表达式,默认情况下总是进行溢出检查,同使用checked一样,会无法通过编译。

若运算是非常量表达式,则是否进行溢出检查,取决于外部因素,包括编译器状态、执行环境参数等。

下例说明了checkedunchecked操作符在非常量表达式中的使用方法

 

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace CountStrDemo
  5. {
  6.     class Program
  7.     {
  8.           //static int x=1000000;
  9.           //static int y=1000000;
  10.           //static int F()
  11.           //{
  12.           //    return checked(x * y); ////运行时抛出OverFlowException异常
  13.           //}
  14.           
  15.           //static int G()
  16.           //{
  17.           //    return unchecked(x * y); //截去高位部分,返回-727379968
  18.           //}
  19.           
  20.           //static int H()
  21.           //{
  22.           //    return x * y;  //依赖于编译器的默认设置,一般是不检查
  23.           //}
  24.         const int x = 1000000;
  25.         const int y = 1000000;
  26.         static int F()
  27.         {
  28.             return checked(x * y);     //编译错误,编译无法通过
  29.         }
  30.         static int G()
  31.         {
  32.             return unchecked(x * y);  //截去高位部分,返回-727379968
  33.         }
  34.         static int H()
  35.         {
  36.             return x * y;     //编译错误,编译无法通过
  37.         }
  38.         static void Main(string[] args)
  39.         {
  40.             //try
  41.             //{
  42.             //    F();
  43.             //}
  44.             //catch (OverflowException ex)
  45.             //{ 
  46.             //}
  47.             
  48.             //int reint = G();
  49.             //Console.WriteLine( reint.ToString() );
  50.           
  51.             //int rein2 = H();
  52.             //Console.WriteLine( rein2.ToString() );
  53.             //Console.ReadLine();
  54.             F();
  55.             int reint = G();
  56.             Console.WriteLine(reint.ToString());
  57.             int rein2 = H();
  58.             Console.WriteLine(rein2.ToString());
  59.             Console.ReadLine();
  60.         }
  61.     }
  62. }
原创粉丝点击