<筆記>Nullable Types

  • 2442
  • 0
  • C#
  • 2010-08-25

摘要:<筆記>Nullable Types

 C#的Nullable Types顧名思義就是允許我們的實值型別可以為NULL,為什麼這裡的型別指實值型別
,因為參考型別(Reference Type)本身就可以為NULL,所以沒必要多此一舉。 例如以下的string就不能用:

 

宣告方式:(以下兩種宣告方式都可以)

Nullable<int> intX = null;  //方式一

int? intX = null;    //方式二

另外Nullable type 這個變數不能直接指定給一般變數,但一般變數可以指定給Nullable type變數,例如:

int? a = 3;
int b = a; // error,必須要經過轉型才行

關於Nullable的運算操作如下:

int? a = null ;
           
int b = a ?? -1;  //方式一:如果a為null時等於??的右邊的值(-1)

int b2 = a.HasValue ? a.GetValueOrDefault() : -1;  //方式二:先利用HasValue來判斷a是否為有值(就是非null),如果有值就執行 ? 右邊,如果是null就執行 : 的右邊

 關於Nullable的邏輯如下:

 

 

bool? x = true;
bool? y = true;

Console.WriteLine(x & y);  //return True
Console.WriteLine(x | y);  //return True
Console.WriteLine(x ^ y);  //return False


bool? x = false;
bool? y = null;

Console.WriteLine(x & y);  //return False
Console.WriteLine((x | y));  //return Null
Console.WriteLine(x ^ y);  //return Null

bool? x = null;
bool? y = null;
Console.WriteLine(x & y);  //return Null
Console.WriteLine((x | y));  //return Null
Console.WriteLine(x ^ y);  //return Null