1、可空類型是 結構的執行個體,可見是實值型別。無法建立基於參考型別的可空類型。(參考型別已支援 null 值)。
2、可空類型表示:基礎實值型別正常範圍內的值+null,Nullable<bool>Nullable<bool> 可以被賦值為 true 或 false或 null。
3、定義:T?和System.Nullable<T>此處的 T 為實值型別。
4、為可空類型賦值與為一般實值型別賦值的方法相同,如 int? x = 10;
5、使用 ?? 運算子分配預設值,當前值為空白的可空類型被賦值給非空類型時將應用該預設值,如 int? x = null; int y = x ?? -1;
。如果基礎類型的值為 null,請使用 屬性返回該基礎 類型所賦的值或預設值,例如 int j = x.GetValueOrDefault()(為null時候返回預設值,否則返回當前值)。
6.HasValue 和 唯讀屬性測試是否為空白和檢索值,例如 if(x.HasValue) j = x.Value。
樣本:
1using System;
2using System.Collections.Generic;
3
4class NullableBasics
5{
6 static void DisplayValue(int? num)
7 {
8 if (num.HasValue == true)
9 {
10 Console.WriteLine("num = " + num);
11 }
12 else
13 {
14 Console.WriteLine("num = null");
15 }
16
17 // 如果 num.HasValue 為 false,則 num.Value 引發 InvalidOperationException
18 try
19 {
20 Console.WriteLine("value = {0}", num.Value);
21 }
22 catch (InvalidOperationException e)
23 {
24 Console.WriteLine(e.Message);
25 }
26 }
27
28 static void Main()
29 {
30 DisplayValue(1);
31 DisplayValue(null);
32 Console.Read();
33
34 }
35}
結果:
num = 1
value = 1
num = null
可為空白的對象必須具有一個值。
樣本:??運算子 1using System;
2
3class NullableOperator
4{
5 static int? GetNullableInt()
6 {
7 return null;
8 }
9
10 static string GetStringValue()
11 {
12 return null;
13 }
14
15 static void Main()
16 {
17 // ?? 運算子樣本。
18 int? x = null;
19
20 // y = x,只有當 x 為 null 時,y = -1。
21 int y = x ?? -1;
22 Console.WriteLine("y == " + y);
23
24 // 將方法的傳回值賦給 i,
25 // 僅當傳回值為 null 時,
26 // 將預設的 int 值賦給 i。
27 int i = GetNullableInt() ?? default(int);
28 Console.WriteLine("i == " + i);
29
30 // ?? 也適用於參考型別。
31 string s = GetStringValue();
32 // 顯示 s 的內容,僅當 s 為 null 時,
33 // 顯示“未指定”。
34 Console.WriteLine("s = {0}", s ?? "null");
35 Console.Read();
36 }
37}
38
結果:
y == -1
i == 0
s = null