What is it? Here’s the scenario


Consider getting the grandchild of a parent object like this:

var g1 = parent.child.child.child;

很明显parent类里面有一个child类的成员,child类又包含child类的成员,这是一个递归调用,child.child.child....可以延伸到无限级。

Okay, so, this is some poor coding because the value of child could be null. If I attempt to ask for the value of child and the containing object is null, a NullReferenceException will be raised and my app will crash.

Here’s what I mean. Consider this:

var g1 = [parent].[child].[null].child;

In this case, I was lucky enough to get two levels in before I hit a null object. But I did hit a null object, and as a result the runtime will thrown an exception.

Instead, you might add some error checking and do this:

// variation 1
var item = this.Parent;
item = (item == null) ? null : item.child;
item = (item == null) ? null : item.child;
var g1 = (parent == null) ? null : item.child;
if (g1 != null) // TODO
 
// variation 2
var g1 = (Child)null;
var item = this.Parent;
if (item != null)
{
item = item.Child;
if (item != null)
{
item = item.Child;
if (item != null)
{
g1 = item.Child;
}
}
}
if (g1 != null) // TODO

Good. Now, this is safe and effective coding. The sample above shows two of many potential approaches. The first using the ternary(三元的) operator in C#, the second using simple conditional blocks.  As we know, we cannot ask for a child property from an object that is null. So, we must check each level.

The conditional code is not difficult to write, but it certainly impacts the size of your code, the complexity of your code, and the readability of your code. Having said that, it’s what we all do today. Code like this shows up all the time and there is nothing wrong with that; but, what if there were a better way.

How the new operator works


Consider getting the grandchild of a parent object like this:

var g1 = parent?.child?.child?.child;
if (g1 != null) // TODO

Wow! That’s the equivalent of testing every single level, but in a single line of code. The “?.” operator is basically saying, if the object to the left is not null, then fetch what is to the right, otherwise return null and halt the access chain.

It’s a wonderful addition to the language’s syntax.

Furthermore


Mad’s Visual Studio User Voice comment continued with a little more explanation of the operator’s implementation. He said, “If the type of e.x (etc) is a non-nullable value type S, then the type of e?.x is S?. Otherwise the type of e?.x is the same as that of e.×. If we can’t tell whether the type is a non-nullable value type (because it is a type parameter without sufficient constraints) we’ll probably give a compile-time error.” This comment, and the idea that a method call or indexer can be to the right of the operator are just candy.

> Now, let’s add NonNullable reference types and we’re really cooking.

此外如果使用!运算符声明类为NonNullable类型,再使用?.运算符时会导致编译错误,如下所示:

public void DoSomething(Order! order)
{
Customer customer = order?.Customer; // Compiler error: order can’t be null
}

因为这时order对象永远不可能为null,C#编译器认为在order后使用?.是多此一举

原文链接

C# 6.0 的?.运算符的更多相关文章

  1. php7.0 新增运算符??

    ??是php7 新增符号 其作用近似于三目运算符 ?: 但存在着细微差别 比较示例代码如图:         $b = $a?$a:2; 三目运算 <=>     $e = $a??'ho ...

  2. 我的MYSQL学习心得(五) 运算符

    我的MYSQL学习心得(五) 运算符 我的MYSQL学习心得(一) 简单语法 我的MYSQL学习心得(二) 数据类型宽度 我的MYSQL学习心得(三) 查看字段长度 我的MYSQL学习心得(四) 数据 ...

  3. Swift3.0变化分享

    Swift 3.0 做出的改变很大,在这篇文章中,我将尽我所能,利用代码样例给大家解释Swift 3.0最重要(要命)的改变,希望大家能够做好升级Swift 3.0 的准备.Swift 3.0的改变不 ...

  4. swift3.0变化总结

    Swift 3.0 做出的改变很大,在这篇文章中,我将尽我所能,利用代码样例给大家解释Swift 3.0最重要(要命)的改变,希望大家能够做好升级Swift 3.0 的准备.Swift 3.0的改变不 ...

  5. 窥探Swift之需要注意的基本运算符和高级运算符

    之前更新了一段时间有关Swift语言的博客,连续更新了有6.7篇的样子.期间间更新了一些iOS开发中SQLite.CollectionViewController以及ReactiveCocoa的一些东 ...

  6. Swift2.3 --> Swift3.0 的变化

    Swift3.0语法变化 首先和大家分享一下学习新语法的技巧: 用Xcode8打开自己的Swift2.3的项目,选择Edit->Convert->To Current Swift Synt ...

  7. swift学习笔记之-高级运算符

    //高级运算符 import UIKit /*高级运算符(Advanced Operators):位运算符.溢出运算符.优先级和结合性.运算符函数.自定义运算符 位运算符: 1.位运算符可以操作数据结 ...

  8. C 运算符优先级

    优先级 运算符 名称或含义 使用形式 结合方向 说明 1 [] 数组下标 数组名[常量表达式] 左到右   () 圆括号 (表达式)/函数名(形参表)   . 成员选择(对象) 对象.成员名   -& ...

  9. Swift - 2.3的代码到3.0的转变

    分享一下学习新语法的技巧:用Xcode8打开自己的Swift2.3的项目,选择Edit->Convert->To Current Swift Syntax- 让Xcode帮我们把Swift ...

随机推荐

  1. Java并发编程:CountDownLatch、CyclicBarrier和Semaphore (总结)

    下面对上面说的三个辅助类进行一个总结: 1)CountDownLatch和CyclicBarrier都能够实现线程之间的等待,只不过它们侧重点不同: CountDownLatch一般用于某个线程A等待 ...

  2. KMP算法的一个简单实现

    今天学习KMP算法,参考网上内容,实现算法,摘录网页内容并记录自己的实现如下: 原文出处: http://www.ruanyifeng.com/blog/2013/05/Knuth%E2%80%93M ...

  3. CentOS 7运维管理笔记(10)----MySQL源码安装

    MySQL可以支持多种平台,如Windows,UNIX,FreeBSD或其他Linux系统.本篇随笔记录在CentOS 7 上使用源码安装MySQL的过程. 1.下载源码 选择使用北理工的镜像文件: ...

  4. python读写不同编码txt文件

        以后整理规范 import os import codecs filenames=os.listdir(os.getcwd()) out=file("name.txt",& ...

  5. SpringMVC学习(四)——处理器Handler的各种常用实现

    代码:http://files.cnblogs.com/files/douJiangYouTiao888/MultiActionController.zip 在使用springMVC的开发过程中,Ha ...

  6. SQL Server ->> SQL Server 2016新特性之 --- Query Store

    前言 SQL Server 2016引入新的查询语句性能监控.调试和优化工具/功能 -- Query Store.以前我们发现一条查询语句性能突然下降,我们要去找出问题的所在往往需要通过调用一些DMV ...

  7. 【NLP_Stanford课堂】语言模型4

    平滑方法: 1. Add-1 smoothing 2. Add-k smoothing 设m=1/V,则有 从而每一项可以跟词汇表的大小相关 3. Unigram prior smoothing 将上 ...

  8. Visio2010新建E-R图

    visio2010没有内置E-R图的模板,需要自己配置模具.步骤如下: 1.文件->新建->基本流程图->右键菱形->添加到新模具->命名为E-R图. 2.更多形状-&g ...

  9. [Errno 14] problem making ssl connection Trying other mirror.

    使用yum安装程序,报错 解决方法: 我的是升级了下curl就可以了   yum update curl

  10. Jenkins安装 CentOS 7上安装Jenkins

    CentOS 7上安装Jenkins Jenkins 安装 只安装不介绍 步骤1:更新CentOS 7 Linux系统管理员的最佳做法之一是使系统保持最新.安装最新的稳定包,然后重新启动.   1 2 ...