[C#]使用可為 Null 的型別

  • 7205
  • 0
  • C#
  • 2012-10-11

[C#]使用可為 Null 的型別

語法 T? 是 System.Nullable<T> 的簡略表示法,其中 T 是實值型別。兩種格式可以互相變更

 

   例:            int? i = null;  是   Nullable<int> i = null; 的簡寫

可為 null 之型別的每個執行個體 (Instance) 有兩個公用唯讀屬性:

  • HasValue

    HasValue 屬於 bool 型別。當變數包含非 null 的值時,該屬性會設定為 true

  • Value

    Value 的型別與基礎型別相同。如果 HasValuetrueValue 會包含有意義的值。如果 HasValuefalse,存取 Value 將會擲回 InvalidOperationException

 

 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int? x = null;//表示x可為null
            if (x.HasValue)
            {
                System.Console.WriteLine(x.Value);
            }
            else
            {
                System.Console.WriteLine("x為null值");
            } 
            Console.Read(); 
        } 
    }
}

參考MSDN


如有錯誤 歡迎指正