zoukankan      html  css  js  c++  java
  • C# 6.0:Null – Conditional 操作符

    在引入nameof操作符的同时,C# 6.0 还引入了Null-Conditional操作符。它使开发者可以检查object引用链中的null值。这个null-conditional 操作符写作"?.",会在引用链中任一个为null时返回null。这避免了对每一级进行null检查。

    假设我们有一个class为Student,它有一个属性Address,同时这个属性的type是一个名为Address的Class。现在我们用下面的代码块来print它的HomeAddress。

    if (student != null && student.Address != null)
    {
        WriteLine(student.Address.HomeAddress);
    }
    else
    {
        WriteLine("No Home Address");
    }
    View Code

    我们可以看到,为了避免null-reference exception,我们不得不检查student是否为null,然后检查student.Address是否为null。

    现在,上面的代码会通过使用null-conditional(?.)操作符来重写成:

    WriteLine(student?.Address?.HomeAddress ?? "No Home Address");

    是不是很帅?不必分别检查每个对象,使用“?.”我们可以同时检查整个引用链。任意一级为null,它都会返回null。下面的图片解释了“?.”是怎么工作的。

    它也可以和方法协同工作,特别是当我们trigger event的时候。比如下面的代码

    if (AddressChanged != null)
    {
        AddressChanged (this, EventArgs.Empty);
    }
    View Code

    使用?.我们可以这样写。

    AddressChanged ?.Invoke(this, EventArgs.Empty)
  • 相关阅读:
    接口interface
    枚举类型
    编写Hello World ts程序
    TypeScript基本类型
    初始TypeScript
    session和cookie自动登录机制
    奇辉机车车号自动识别系统介绍
    AForge.NET 设置摄像头分辨率
    工作感概—活到老xio到老
    Scala学习二十二——定界延续
  • 原文地址:https://www.cnblogs.com/yuwen/p/4173444.html
Copyright © 2011-2022 走看看