当前位置: 移动技术网 > IT编程>开发语言>c# > C#入门之checked和unchecked的区别实例解析

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

2019年07月18日  | 移动技术网IT编程  | 我要评论

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网