C# Keywords Series 3 checked&unchecked&decimal

    本篇文章主要关于checked和unchecked 以及decimal 的用途。对于这个系列关键字的顺序倒没什么考虑,主要针对些自己先前从没见过或是还不熟悉的写的。

    checked

    checked 用于保证能catch到整型数据溢出的情况,似乎只针对整型,int,long...对于浮点型的不支持。像下面的声明会直接报编译器错误

    

  int i = 2147483647 + 10;

    // Error : The Operation overflows at compile time in checked mode

    如果像下面的声明,编译器是不会报错,int类型只会默认的赋值为-2147483639.

   

  int ten = 10;
  int i2 = 2147483647 + ten;
  Console.WriteLine(i2);
  // Output: -214748639


    而checked的作用就是catch到这样的溢出异常,先上代码:

   

   public static void  TestChecked()
        {
          
            int ten = 10;
      
            try
            {
                checked
                {
                    int i2 = int.MaxValue + ten;
                    Console.WriteLine(i2);
                }
            }
            catch (System.OverflowException e)
            {
                Console.WriteLine(e.ToString());
            }
        }
         //Output: System.OverflowException: Arithmetic operation resulted in an overflow.
        // at ConsoleApplication.Program.TestChecked() in c:\Users\v-isyang\Documents\
       // Visual Studio 2012\Projects\Learning\ConsoleApplication\Program.cs:line 26


    这样我们就成功获取了溢出异常

    unchecked

    从字面上看自然是忽略异常,像上面的第一个例子,如果我不希望编译器报错,给上默认值就行,那我就需要加上unchecked,看代码

   

public static void TestUnchecked()
{
   int i1;
        unchecked
        {
            int1 = 2147483647 + 10;
        }
        int1 = unchecked(ConstantMax + 10);

        // The sum of 2,147,483,647 and 10 is displayed as -2,147,483,639.
        Console.WriteLine(int1);
}


    只针对整型数据的检测,这只是关于checked 和 unchecked 的简单说明。

    decimal

    decimal高精度小数类型,不是浮点型数据,一开始就纳闷了,为什么还有这个小数类型,它和float\double浮点型有什么区别,自然就想看它的内部。这里推荐一个反射的工具:ISpy,可以自己网上download。

     decimal相对于double更精确,double是二进制数据,decimal 是微软自己定义的类型,而且它的加减乘除操作是自己写方法的,附上代码:

   

[__DynamicallyInvokable, SecuritySafeCritical]
public static decimal Add(decimal d1, decimal d2)
{
	decimal.FCallAddSub(ref d1, ref d2, 0);
	return d1;
}

   而double的操作是直接调用CPU的运算的,这是主要区别 。decimal 类型是适合财务和货币计算的   128   位数据类型。double类型存在精度损失,上代码

  

  double dd = 10000000000000000000000d;
            dd += 1;
            Console.WriteLine ( "{0:G50}", dd );
            // Output : 10000000000000000000000


 

    decimal则不存在这样的精度损失。decimal的maxvalue比float还小,但是它占16字节,double是8字节,single(float)是4字节。

   本篇博客到此为止,欢迎纠错!

   

   

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值