zoukankan      html  css  js  c++  java
  • C# nullable<T> 用法小结

    今天在园子里看到一个关于C#中对于可空类型的描述的帖子,感觉不错于是自己写了个小例子尝试下。

    在C#中,对于可空类型描述为:Nullable<T>, 它表示该类型是可以为空的一个类型。它被定义为一个结构(struct)而非一个类(class)... 在这里用一个小Demo来看看它的用法

    int? intTest;
    int? nullIntValue = new Nullable<int>();

    intTest = 999;

    try
    {
      //1. output an interger value
      Console.WriteLine("output an interger value: {0}", intTest);

      //2. output an boxed (int) value
      object boxedObj = intTest;
      Console.WriteLine("output an boxed integer type: {0}", boxedObj.GetType());

      //3. output an unboxed int value
      int normalInt = (int)boxedObj;
      Console.WriteLine("output an unboxed integer value: {0}", normalInt);

      //4. output an nullable object
      object nullObj = nullIntValue;
      Console.WriteLine("output an nullable equals null ? : {0}", (nullObj == null));

      ////output an nullable value (Error: non refferenced)
      //int nullIntTest = (int)nullObj;
      //Console.WriteLine("output an nullable value: {0}", nullIntTest);

      //5. output an value of nullable object
      Nullable<int> nullIntTest = (Nullable<int>)nullObj;
      Console.WriteLine("Unboxed an nullable value: {0}", nullIntTest);  

      //int nullIntTest = (int)nullObj;
      //Console.WriteLine("Unboxed an nullable value: {0}", nullIntTest);

      
    }
    catch (Exception ex)
    {
      Console.WriteLine("Error happend: {0}", ex.Message);
    }

    Console.ReadKey();

    输出结果如下:

    在上面这段代码中,我尝试了将一个不为空的可空值类型实例装箱后的值分别拆箱为普通的值类型以及可空值类型(1,2,3)。之后,我又将一个没有值的可空值类型实例testNull装箱为一个空引用,之后又成功的拆箱为另一个没有值的可空值类型实例(4,5)。如果此时我们直接将它拆箱为一个普通的值类型,编译器会抛出一个NullReferenceException异常。。。

  • 相关阅读:
    angular.isDefined()
    angular.isDate()
    angular.isArray()
    .NET中栈和堆的比较
    SQL Server 2012配置Always On可用性组
    一分钟了解负载均衡的一切
    C# 线程并发锁
    获取Http请求参数
    什么是WCF
    Bitmap算法应用
  • 原文地址:https://www.cnblogs.com/atuotuo/p/4843308.html
Copyright © 2011-2022 走看看