C#操作符 “??”
?? 运算符称为 null 合并运算符,用于定义可以为 null 值的类型和引用类型的默认值。 如果此运算符的左操作数不为 null,则此运算符将返回左操作数;否则返回右操作数。
可以为 null 的类型可以包含值,或者可以是未定义的。 ?? 运算符定义当可以为 null 的类型分配给非可以为 null 的类型时返回的默认值。 如果在尝试将可以为 null 值的类型分配给不可以为 null 值的类型时没有使用 ?? 运算符,则会生成编译时错误。 如果使用强制转换,且当前还未定义可以为 null 值的类型,则会引发InvalidOperationException 异常。
有关更多信息,请参见可以为 null 的类型(C# 编程指南)。
即使 ?? 运算符的两个参数都是常量,也不能将其结果视为常量。
1 class NullCoalesce 2 { 3 static int? GetNullableInt() 4 { 5 return null; 6 } 7 8 static string GetStringValue() 9 { 10 return null; 11 } 12 13 static void Main() 14 { 15 // ?? operator example. 16 int? x = null; 17 18 // y = x, unless x is null, in which case y = -1. 19 int y = x ?? -1; 20 21 // Assign i to return value of method, unless 22 // return value is null, in which case assign 23 // default value of int to i. 24 int i = GetNullableInt() ?? default(int); 25 26 string s = GetStringValue(); 27 // ?? also works with reference types. 28 // Display contents of s, unless s is null, 29 // in which case display "Unspecified". 30 Console.WriteLine(s ?? "Unspecified"); 31 } 32 }