早期版本的C#更新介绍了可为 null 的类型和 null 合并运算符的概念,??在处理可以为 null 值的值时减少样本代码量。 C#6将继续此主题,其中包含 “null 条件运算符”?.。 当在表达式的右侧的对象上使用时,如果对象不 null,则为 null 条件运算符将返回成员值,否则 null:
var ss = new string[] { "Foo", null };
var length0 = ss [0]?.Length; // 3
var length1 = ss [1]?.Length; // null
var lengths = ss.Select (s => s?.Length ?? 0); //[3, 0]
(length0 和 length1 都推断为类型 int?)
上一示例中的最后一行显示了 ? 的 null 条件运算符与 ?? null 合并运算符的组合。 新C#的 6 null 条件运算符返回数组中第2个元素上的null,此时,空合并运算符将在中启动,并向lengths的数组提供0(当然,这是特定于问题的)。
对于许多应用程序而言,null 条件运算符应在很大程度上减少不必要的样本的空检查量。
由于歧义,对 null 条件运算符有一些限制。 你不能立即使用带括号的参数列表的 ?,因为你可能希望使用委托:
SomeDelegate?("Some Argument") // Not allowed
不过,Invoke 可用于将 ? 与自变量列表分开,并且仍是对 null检查样本块的标记改进:
public event EventHandler HandoffOccurred;
public override bool ContinueUserActivity (UIApplication application, NSUserActivity userActivity, UIApplicationRestorationHandler completionHandler)
{
HandoffOccurred?.Invoke (this, userActivity.UserInfo);
return true;
}
摘自https://docs.microsoft.com/zh-cn/xamarin/cross-platform/platform/csharp-six