C# 6.0 的?.运算符

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后使用?.是多此一举

 

 

原文链接

 

转载于:https://www.cnblogs.com/OpenCoder/p/9796385.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
This new 7th edition of Pro C# 6.0 and the .NET 4.6 Platform has been completely revised and rewritten to reflect the latest changes to the C# language specification and new advances in the .NET Framework. You'll find new chapters covering all the important new features that make .NET 4.6 the most comprehensive release yet, including:, A Refined ADO.NET Entity Framework Programming ModelNumerous IDE and MVVM Enhancements for WPF Desktop DevelopmentNumerous updates to the ASP.NET Web APIs, This comes on top of award winning coverage of core C# features, both old and new, that have made the previous editions of this book so popular. Readers will gain a solid foundation of object-oriented development techniques, attributes and reflection, generics and collections as well as numerous advanced topics not found in other texts (such as CIL opcodes and emitting dynamic assemblies)., The mission of this book is to provide you with a comprehensive foundation in the C# programming language and the core aspects of the .NET platform plus overviews of technologies built on top of C# and .NET (ADO.NET and Entity Framework, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), ASP.NET (WebForms, MVC, WebAPI).). Once you digest the information presented in these chapters, you’ll be in a perfect position to apply this knowledge to your specific programming assignments, and you’ll be well equipped to explore the .NET universe on your own terms., What You Will Learn:, Be the first to understand the .NET 4.6 platform and C# 6.Discover the ins and outs of the leading .NET technology.Learn from an award-winning author who has been teaching the .NET world since version 1.0.Find complete coverage of XAML, .NET 4.6 and Visual Studio 2015 together with discussion of the new Windows Runtime.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值