x?.y?.z是什么意思?

时间:2014-08-07 18:27:35

标签: c# pattern-matching

Pattern Matching in C#的草稿规范包含以下代码示例:

Type? v = x?.y?.z; 
if (v.HasValue) {
    var value = v.GetValueOrDefault();     
    // code using value 
} 

我理解Type?表示Type可以为空,但假设xyz是本地人,x?.y?.z是什么是什么意思?

3 个答案:

答案 0 :(得分:98)

请注意,此语言功能仅适用于C#6及更高版本。

它实际上相当于:

x == null ? null
   : x.y == null ? null
   : x.y.z

换句话说,这是一种“安全”的方式x.y.z,其中任何属性都可能为空。

null coalescing operator (??)也是相关的,它提供了替换null的值。

答案 1 :(得分:29)

这是Null-propagating operator / Null-Conditional Operator ?. C#6.0中新建议的功能

x?.y?.z表示

  • 首先,检查x是否为空,然后检查 y,否则返回null,
  • 第二,当x不为null时,检查y,如果它不为null,则返回z,否则返回null。

最终回报值为znull

如果x为空,如果没有此运算符,则访问x.y将引发空引用异常,Null-Conditional运算符有助于避免显式检查null。

这是一种避免空引用异常的方法。

请参阅:Getting a sense of the upcoming language features in C#

  

8 - 空条件运算符

     

有时代码往往会在null检查中淹没一点。该   null-conditional运算符只允许您访问成员和元素   当接收者不为null时,否则提供null结果:

int? length = customers?.Length; // null if customers is null

答案 2 :(得分:2)

 this.SlimShadies.SingleOrDefault(s => s.IsTheReal)?.PleaseStandUp();

基本上

相关问题