C#2.0中的可空類型

來源:互聯網
上載者:User

1、可空類型是 結構的執行個體,可見是實值型別。無法建立基於參考型別的可空類型。(參考型別已支援 null 值)。
2、可空類型表示:基礎實值型別正常範圍內的值+null,Nullable<bool>Nullable<bool> 可以被賦值為 truefalsenull。
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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.