獲取可空型別的值

鑑於以下可空的 int

int? i = 10;

如果需要預設值,你可以使用空合併運算子 GetValueOrDefault 方法分配一個,或者在賦值之前檢查是否為 nullable int HasValue

int j = i ?? 0;
int j = i.GetValueOrDefault(0);
int j = i.HasValue ? i.Value : 0;

以下用法始終不安全。如果 i 在執行時為 null,則會丟擲 System.InvalidOperationException。在設計時,如果未設定值,則會出現 Use of unassigned local variable 'i'錯誤。

int j = i.Value;