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. Scarpy+selenium 结合使用

    首先要先在spider对象实例化时,同时实例化一个浏览器对象 # -*- coding: utf-8 -*- import scrapy from selenium import webdriver ...

  2. div 旋转

    -webkit-transform:rotate(120deg); -moz-transform:rotate(120deg); -o-transform:rotate(120deg); /* fil ...

  3. 浅谈JavaScript之function用括号包起来

    (function a(){}) (命名函数表达式)会返回这个函数(不会执行),但是在括号外面无法调用该函数,需要一个变量接收这个函数,var fun = (function a(){}),一般这个用 ...

  4. CentOS 7运维管理笔记(12)----GUI配置工具Webmin的安装

    早期的Linux系统管理员或是Web管理员在修改服务器配置时使用最多的就是vi编辑器,但是现在越来越多的基于GUI界面的配置工具出现了,毕竟人们还是喜欢以直接的可视化的方式来修改服务器的配置,而不是再 ...

  5. How to use Log4cplus

    Introduction Log4cplus is derived by the popular Log4j written in java.<br>This tutorial show ...

  6. restful知识点之二restframework视图

    restful协议理解:面向资源开发 restful协议 ---- 一切皆是资源,操作只是请求方式 ----book表增删改查 /books/ books /books/add/ addbook /b ...

  7. maven项目怎么引入另一个maven项目

    yi      最近在做项目的时候,遇到多模块(mudul)开发,里面的maven包相互引用,刚开始不知道怎么导入,费了好大尽总算搞定了.把遇到的问题记录下. 1.怎么导入依赖的maven模块 选择I ...

  8. html5自我总结

    2017年7月30日 合抱之木,生于毫末.九层之台,起于累土.软件行业要熟记和训练的东西有很多,在此,写一下如何快速搭建html及自我见解(这里只介绍我自己用到的,还有部分存在但是用不到的就不讲解了) ...

  9. Redis的系统级命令

    文章建立一个统一的认识就是Redis的版本是3.2.8 1:BGREWRITEAOF(bgrewriteaof) 执行一个 AOF文件 重写操作.重写会创建一个当前 AOF 文件的体积优化版本. 即使 ...

  10. tomcat运行报错Failed to start component [StandardEngine[Catalina].StandardHost[localhost].

    tomcat运行报错Failed to start component [StandardEngine[Catalina].StandardHost[localhost].多半情况是找不到jar包 解 ...