標籤:des style blog http color io os ar 使用
- Visual Studio 2008
- Visual Studio 2005
- Visual Studio 2013
- Visual Studio 2012
?? 運算子稱為 null 合并運算子,用於定義可以為 null 值的類型和參考型別的預設值。如果此運算子的左運算元不為 null,則此運算子將返回左運算元;否則返回右運算元。
備忘
可為 Null 的型別可以包含值,或者可以是未定義的。?? 運算子定義當可為 Null 的型別分配給非可為 Null 的型別時返回的預設值。如果在嘗試將可以為 null 值的類型分配給不可以為 null 值的類型時沒有使用 ?? 運算子,則會產生編譯時間錯誤。如果使用強制轉換,且當前還未定義可以為 null 值的類型,則會引發 InvalidOperationException 異常。
有關更多資訊,請參見可為 Null 的型別(C# 編程指南)。
即使 ?? 運算子的兩個參數都是常量,也不能將其結果視為常量。
樣本C#複製
class NullCoalesce{ static int? GetNullableInt() { return null; } static string GetStringValue() { return null; } static void Main() { // ?? operator example. int? x = null; // y = x, unless x is null, in which case y = -1. int y = x ?? -1; // Assign i to return value of method, unless // return value is null, in which case assign // default value of int to i. int i = GetNullableInt() ?? default(int); string s = GetStringValue(); // ?? also works with reference types. // Display contents of s, unless s is null, // in which case display "Unspecified". Console.WriteLine(s ?? "Unspecified"); }}
?? 運算子(C# 參考)