?? 運算符稱為 null 合并運算符,用于定義可以為 null 值的類型和引用類型的默認值。 如果此運算符的左操作數不為 null,則此運算符將返回左操作數;否則返回右操作數。
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"); }}新聞熱點
疑難解答