萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C# 可空類型深度解析:Nullable 底層實現、運算提升、?? 運算符與高效能模式

核心定義

Nullable(簡寫 T?)是**值類型**的「可為 null」包裝器,定義於 System.Nullable<T>(T : struct)。它是**結構體**,非類,因此本身不可為 null,但可表示「無值」狀態。

源碼級結構(簡化)


[Serializable]
public struct Nullable where T : struct {
    private readonly bool hasValue;   // 是否有值
    private readonly T value;         // 底層值

    public Nullable(T value) { this.value = value; this.hasValue = true; }

    public bool HasValue => hasValue;
    public T Value {
        get {
            if (!hasValue) throw new InvalidOperationException("Nullable object must have a value.");
            return value;
        }
    }
    public T GetValueOrDefault() => value;
    public T GetValueOrDefault(T defaultValue) => hasValue ? value : defaultValue;

    // 隱式轉換 T -> T?
    public static implicit operator Nullable(T value) => new Nullable(value);
    // 顯式轉換 T? -> T
    public static explicit operator T(Nullable nullable) => nullable.Value;

    // 相等性/比較/ToString/GetHashCode 等...
}

聲明與初始化


// 兩種等價語法
Nullable a = 5;
int? b = 5;

int? c = null;           // HasValue = false
int? d = default;        // 同上
int?[] arr = {1, 2, null, 4}; // 可空類型數組

轉換規則

轉換方向方式備註
T → T?隱式int? x = 5;
T? → T顯式轉換 / .Valueint y = (int)x; 或 x.Value,HasValue=false 拋異常
T? → U?隱式(若 T→U 隱式)int? → long? 、 double?
T? → U顯式long? → int 需雙重轉換

提升運算符

可空類型**自動提升**所有預定義一元/二元/比較/相等運算符:

  • 操作數任一為 null → 結果為 null(除 &&, || 短路邏輯)。
  • 否則解包運算,結果重新包裝為 T?。

int? a = 10, b = null;
Console.WriteLine(a + 5);      // 15
Console.WriteLine(a + b);      // null
Console.WriteLine(a * 2);      // 20
Console.WriteLine(a == b);     // False
Console.WriteLine(b == null);  // True
Console.WriteLine(a > b);      // False (任一 null 比較為 false)

邏輯運算符短路行為(關鍵差異)


bool? x = true, y = null, z = false;
Console.WriteLine(x & y);   // null  (非短路 &,雙方評估)
Console.WriteLine(x && y);  // null  (短路 &&,x=true 需評估 y)
Console.WriteLine(z && y);  // false (短路,z=false 直接返回 false,不評估 y)
Console.WriteLine(x | y);   // true  (非短路 |)
Console.WriteLine(x || y);  // true  (短路 ||,x=true 直接返回 true)

**結論**:&&/|| 保留短路語義,可能返回 bool?(三值邏輯);&/| 總評估兩側,結果為 bool?。

?? 空合併運算符 & ??= 賦值(C# 8.0+)


int? a = null;
int b = a ?? 42;        // 42
int? c = a ?? 10;       // 10 (類型 int?)

string s = null;
s ??= "default";        // 等價 s = s ?? "default"
Console.WriteLine(s);   // default

// 鏈式
int? v = null;
int result = v ?? GetDefault() ?? 100; // 依次評估直到非 null

Nullable.GetValueOrDefault() 進階用法


int? x = null;
Console.WriteLine(x.GetValueOrDefault());      // 0 (default(T))
Console.WriteLine(x.GetValueOrDefault(-1));    // -1

// 等價模式匹配 (C# 7+)
int y = x switch { null => -1, var v => v };

高效能模式:避免隱式裝箱/拆箱


// 慢:介面調用導致裝箱
IComparable cmp = 5;
int? n = 5;
Console.WriteLine(cmp.CompareTo(n)); // 裝箱 n

// 快:直接用泛型/約束
int Compare(T? a, T? b) where T : struct, IComparable {
    if (!a.HasValue || !b.HasValue) return 0;
    return a.Value.CompareTo(b.Value);
}

IL 視角:編譯器生成的代碼

int? a = 1; int? b = 2; var c = a + b; 編譯為:


Nullable a = new Nullable(1);
Nullable b = new Nullable(2);
Nullable c = a.HasValue & b.HasValue
    ? new Nullable(a.GetValueOrDefault() + b.GetValueOrDefault())
    : new Nullable();

大量可空運算會產生顯著 IL 體積,**熱路徑建議改用非可空 + 哨兵值**或 Option<T> 模式。

最佳實踐清單

  1. **領域建模優先用 T?** 表示「可選值」,避免魔術數(-1, 0, int.MaxValue)。
  2. **公開 API 邊界** 用 T? 明確表達可選性,內部熱路徑轉為非可空。
  3. **避免巢狀可空**:int?? 編譯錯誤,Nullable> 非法。
  4. **序列化**:JSON.NET/System.Text.Json 自動處理 null ↔ HasValue=false。
  5. **模式匹配解構**:if (x is { HasValue: true } val) 或 switch 表達式。
  6. **readonly struct 包裝**:大型可空值類型可定義 readonly struct Optional 避免防禦性複製。

總結

Nullable 是值類型「可選性」的一等公民表達,編譯器/運行時深度整合(提升運算符、??、模式匹配)。理解其**結構體本質、隱式/顯式轉換、三值邏輯、IL 展開代價**,能在領域建模與高效能代碼間游刃有餘。

copyright © 萬盛學電腦網 all rights reserved