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. dokcer安装并开机自启动服务

    linux内核最好是3.10以上.不过本次使用的是centos6.5 内核2.6 1.yum -y install docker-io 如果出现: 需要安装yum源: 3.service docker ...

  2. Editplus编辑器在php文件中变色显示设置

    咋editplus中我们编辑时有时会遇到不变色的问题,那么怎么设置呢,从语法配置就好,如下:

  3. 空白符对HTML结构的影响与解决方案

    何为空白符? 空白符: 空格.制表符.换行符 注意:浏览器在解析HTML时会把所有空白符合并成一个空格 空白符对HTML结构的影响 HTML5中<textarea>标签placeholde ...

  4. 消息循环中的TranslateMessage函数和DispatchMessage函数,特别注意WM_TIMER消息

    原文:http://www.cnblogs.com/xingrun/p/3583357.html TranslateMessage函数 函数功能描述:将虚拟键消息转换为字符消息.字符消息被送到调用线程 ...

  5. 第三次Scrum编码冲刺

    1.小组成员 周 斌 舒 溢 许嘉荣 唐 浩 黄欣欣 廖帅元 刘洋江 薛思汝 2.个人在小组第三次冲刺的任务及其完成情况描述. 这次小组活动中我负责测试程序的实现情况,确保程序的每个模块都能正常运行, ...

  6. C++中long是什么类型

    long long本质上还是整型,只不过是一种超长的整型. int型:32位整型,取值范围为-2^31 ~ (2^31 - 1) .long:在32位系统是32位整型,取值范围为-2^31 ~ (2^ ...

  7. shp文件导入mysql5.6.15

    百度了一下 方法大致相同,就是提供的资源都缺斤短两还在细节上有差异.所以上传一份正确的. 0.将cygwin1.dll拷贝到system32目录下面1.将shp以及shp的相关文件和DOShere的d ...

  8. SpringMVC学习(六)——@InitBinder注解

    有些类型的数据是无法自动转换的,比如请求参数中包含时间类型的数据,无法自动映射到Controller里的Date参数.需要使用@initBinder注解为binder提供一个数据的转换器,这个转换器可 ...

  9. .net通过代码发送邮件

    关键代码: 需要引用命名空间: using System.Net.Mail;using System.Net; MailMessage mailObj = new MailMessage(); mai ...

  10. 设计模式:访问者(Visitor)模式

    设计模式:访问者(Visitor)模式 一.前言    什么叫做访问,如果大家学过数据结构,对于这点就很清晰了,遍历就是访问的一般形式,单独读取一个元素进行相应的处理也叫作访问,读取到想要查看的内容+ ...