zoukankan      html  css  js  c++  java
  • 探讨c#中的unchecked是什么意思,起什么作用?

    Checked与Unchecked     
    对于因为整数类型参与算术操作和类型转换时产生的“溢出异常”——System.OverflowException,在某些算法来讲不算真正的“异常”,相反这种溢出常常为程序所用。C#通过引入checked和unchecked关键字来控制这种特殊情况的需求。它们都可以加于一个语句块前(如:checked{……}),或者一个算术表达式前(如:unchecked(x+y)),其中加checked标志的语句或表达式如果发生算术溢出,则抛出System.OverflowException类型的异常,而加unchecked标志的语句发生算术溢出时,则不抛出异常。下面是一个示例:   

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ConsoleApplication1
    {
        
        class Program
        {
            private delegate string GetAString();
    
            static void Main(string[] args)
            {
                int num1 = 100000, num2 = 100000,result = 0;
                checked
                {
                    try { result = num1 * num2; }
                    catch (Exception e) { Console.WriteLine(e); }
                    finally { Console.WriteLine(result); }
                }
                unchecked
                {
                    try { result = num1 * num2; }
                    catch (System.OverflowException e) { Console.WriteLine(e); }
                    finally { Console.WriteLine(result); }
                }
                try { result = num1 * num2; }
                catch (System.OverflowException e) { Console.WriteLine(e); }
                finally { Console.WriteLine(result); }
                
                Console.Read();
            }
        }
        
    }
    

      


    程序输出:     

    由此看出,默认情况下是unchecked

     

    可以看到同样的算术操作,用checked抛出了溢出异常,而unchecked只是将溢出的位丢弃而得到剩下的32位组成的十进制整数值。值得指出的是可以用“/checked”编译器选项指定整个文件的代码为checked语义,如果没有指定则默认为unchecked。如果同时在程序代码中指定checked或unchecked标志,又有了checked编译器选项,则除了标志为unchecked的代码外,其余的都有checked语义。

  • 相关阅读:
    Wedge 100-32X 100GbE Data Center Switch
    openstack参考资料
    进程调度
    进程管理 之 基本概念
    Linux设备驱动程序 之 中断和锁
    Linux设备驱动程序 之 工作队列
    Linux设备驱动程序 之 tasklet
    Linux设备驱动程序 之 软中断
    Linux设备驱动程序 之 中断下半部
    Linux设备驱动 之 中断处理程序
  • 原文地址:https://www.cnblogs.com/niaowo/p/4499008.html
Copyright © 2011-2022 走看看