<筆記>Nullable Types

来源:互联网 发布:mac修图 编辑:程序博客网 时间:2024/06/15 20:06

<筆記>Nullable Types

http://www.dotblogs.com.tw/boei/archive/2010/08/19/17309.aspx

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

 

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

1Nullable<int> intX = null;  //方式一
2 
3int? intX = null;    //方式二

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

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

關於Nullable的運算操作如下:

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

 關於Nullable的邏輯如下:

 

 

01bool? x = true;
02bool? y = true;
03 
04Console.WriteLine(x & y);  //return True
05Console.WriteLine(x | y);  //return True
06Console.WriteLine(x ^ y);  //return False
07 
08 
09bool? x = false;
10bool? y = null;
11 
12Console.WriteLine(x & y);  //return False
13Console.WriteLine((x | y));  //return Null
14Console.WriteLine(x ^ y);  //return Null
15 
16bool? x = null;
17bool? y = null;
18Console.WriteLine(x & y);  //return Null
19Console.WriteLine((x | y));  //return Null
20Console.WriteLine(x ^ y);  //return Null
原创粉丝点击