C#入门之checked和unchecked的区别实例解析


本文以实例形式对比测试了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


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3