其中:
block
包含要在已检查上下文中计算的表达式的语句块。
expression
要在已检查上下文中计算的表达式。注意表达式必须位于括号 ( ) 内。
备注
在已检查的上下文中,如果表达式产生目标类型范围之外的值,则结果取决于表达式是常数还是非常数。常数表达式导致编译时错误,而非常数表达式在运行时计算并引发异常。
如果既未使用 checked 也未使用 unchecked,则在编译时常数表达式使用默认溢出检查(即 checked)。否则,如果表达式为非常数,则运行时溢出检查取决于其他因素(如编译器选项和环境配置)。
下面三个示例在非常数表达式上演示 checked 和 unchecked 运算符。所有这三个示例都使用相同的算法,但使用不同的检查上下文。溢出检查在运行时计算。
示例 1:使用 checked 表达式。
示例 2:使用 unchecked 表达式。
示例 3:使用默认溢出检查。
只有第一个示例在运行时引发溢出异常,在那种情况下,您可以选择或者转到调试模式,或者中止程序执行。其他两个示例产生截断的值。
有关如何使用 checked 和 unchecked 语句的信息,请参见 unchecked 示例。
示例 1
// statements_checked.cs
// The overflow of non-constant expressions is checked at run time
using System;

class OverFlowTest
{
   static short x = 32767;   // Max short value
   static short y = 32767;

   // Using a checked expression
   public static int myMethodCh()
   {
      int z = 0;

      try
      {
        z =  checked((short)(x + y));
      }
      catch (System.OverflowException e)
      {
        System.Console.WriteLine(e.ToString());
      }
      return z;   // Throws the exception OverflowException
   }

   public static void Main()
   {
      Console.WriteLine("Checked output value is: {0}", myMethodCh());
   }
}
示例输出
当运行程序时,它引发 OverflowException 异常。您可以调试程序或中止执行。
System.OverflowException: An exception of type System.OverflowException was thrown.
   at OverFlowTest.myMethodCh()
Checked output value is: 0
示例 2
// statements_checked2.cs
// Using unchecked expressions
// The overflow of non-constant expressions is checked at run time
using System;

class OverFlowTest
{
   static short x = 32767;   // Max short value
   static short y = 32767;

   public static int myMethodUnch()
   {
      int z =  unchecked((short)(x + y));
      return z;   // Returns -2
   }

   public static void Main()
   {
      Console.WriteLine("Unchecked value is: {0}", myMethodUnch());
   }
}
输出
Unchecked value is: -2
示例 3
// statements_checked3.cs
// Using default overflow checking
// The overflow of non-constant expressions is checked at run time
using System;

class OverFlowTest
{
   static short x = 32767;   // Max short value
   static short y = 32767;

   public static int myMethodUnch()
   {
      int z =  (short)(x + y);
      return z;   // Returns -2
   }

   public static void Main()
   {
      Console.WriteLine("Default checking ouput value is: {0}", myMethodUnch());
   }
}
输出
Default checking ouput value is: -2

posted on 2005-09-01 15:41  流浪的猫  阅读(338)  评论(0编辑  收藏  举报