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)
  • 相关阅读:
    HDU1029 Ignatius and the Princess IV
    UVA11039 Building designing【排序】
    UVA11039 Building designing【排序】
    POJ3278 HDU2717 Catch That Cow
    POJ3278 HDU2717 Catch That Cow
    POJ1338 Ugly Numbers(解法二)
    POJ1338 Ugly Numbers(解法二)
    UVA532 Dungeon Master
    UVA532 Dungeon Master
    POJ1915 Knight Moves
  • 原文地址:https://www.cnblogs.com/yuwen/p/4173444.html
Copyright © 2011-2022 走看看