1 ?运算符介绍
Null 条件运算符在 C# 6 及更高版本中可用,仅当操作数的计算结果为非 null 时,null 条件运算符才会将成员访问 或元素访问 运算应用于其操作数;否则,将返回 null
1.1 如果 a 的计算结果为 null,则 a?.x 或 a?[x] 的结果为 null。
1.2 如果 a 的计算结果为非 null,则 a?.x 或 a?[x] 的结果将分别与 a.x 或 a[x] 的结果相同。
微软官方
举例:
List<T> test = "查询数据";
test.FirstOrDefault(w => w.Name == "Test")?.F_Num ?? 0
2 ??运算符介绍:
如果左操作数的值不为 null,则 null 合并运算符 ?? 返回该值;否则,它会计算右操作数并返回其结果。 如果左操作数的计算结果为非 null,则 ?? 运算符不会计算其右操作数。
微软官方
举例:
int? a = null;
int b = a ?? -1;
Console.WriteLine(b); // output: -1