今天在園子里看到一個關於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異常。。。