定义
??被称为【可空合并】运算符,是一个二目运算符,操作参数两枚,其完成的功能为对左参数判断之后进行赋值。
返回结果:如果左操作数不为空,则返回左操作数本身;如果左操作书为空,则返回右操作数。
格式:object1 ?? object2
//伪代码示例 obejct NullCoalescingFunc( obejct object1,obejct obejct2) { if(object1!=null) return object1; else return object2; }
备注
可空类型(Nullable type)的变量既可以表示原类型取值范围内的值,也可以给其赋值为NULL(关于C#的可空类型是什么类型,此文暂且不论,读者自己百度先)。所以假如左操作数是一个值为NULL的可空类型变量时,就可以使用??运算符来返回适当的值(右操作数的值)。假如开发者尝试将一个可空类型变量的值赋给一个不可空类型的变量时,就会引起编译错误不通过。亦或者在前后上下文没有声明可空类型的变量时,开发者使用强制转换,会引发 InvalidOperationException 异常。
测试代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class NullCoalesce { static int? GetNullableInt() { return null; } static string GetStringValue() { return null; } static void Main() { int? x = null; int y = x ?? -1; Console.WriteLine(string.Format("x={0},y={1}",x,y)); int i = GetNullableInt() ?? default(int); Console.WriteLine(string.Format("i={0} ", i)); string s = GetStringValue(); Console.WriteLine(s ?? "Unspecified"); Console.ReadKey(); } }
输出
详细可见这一篇:
https://www.runoob.com/csharp/csharp-nullable.html

