C# 6.0 (C# vNext) 新功能之:Null-Conditional Operator(转)

Null-Conditional Operator 也叫 Null propagating operator 也叫 Safe Navigation Operator

看名字,应该就有点概念了。如果还不知道,提示一下:
有个叫 Conditional Operator 条件运算符(?:)
也就是常会用到的:

[csharp] view plain copy
 
  1. var result = (1 > 2) ? true : false;  


当括号内的结果为 true 时,回传第一个值,如果为 false 回传第二个值。

另外有一种:null-coalescing operator (??)
比如:
int? x = null;
int y = x ?? -1;
当 x 不为 null 时,则将其值给 y, 否则 y 被指定为 -1

C# 6.0 新的 Null-Conditional Operator 应该可以叫做 null条件运算符
使用如下:

C# 6.0 之前的写法:

[csharp] view plain copy
 
  1. var temp = GetCustomer();  
  2. string name = (temp == null) ? null : temp.name;  


C# 6.0 的新写法

[csharp] view plain copy
 
  1. var temp = GetCustomer()?.name;  


也就是当 GetCustomer() 回传值不为 null 时,取 name 的值给 temp 变量

其他的例子:

[csharp] view plain copy
 
  1. x?.Dispose(); // 当 x 不为 null 时才呼叫 Dispose 方法  


例子:

[csharp] view plain copy
 
  1. event EventHandler OnFired;  
  2. void Fire()  
  3. {  
  4.     OnFired?.Invoke(this, new EventArgs());  
  5. }  


当 OnFired 事件不为 null (有人注册该事件)时,才呼叫 Invoke 方法

例子:
以前的写法:

[csharp] view plain copy
 
  1. public static string Truncate(string value, int length)  
  2. {  
  3.   string result = value;  
  4.   if (value != null)   
  5.   {  
  6.     result = value.Substring(0, Math.Min(value.Length, length));  
  7.   }  
  8.   return result;  
  9. }  


新写法:

[csharp] view plain copy
 
  1. public static string Truncate(string value, int length)  
  2. {            
  3.   return value?.Substring(0, Math.Min(value.Length, length));  
  4. }  

 

原文地址:https://www.cnblogs.com/lip-blog/p/7690868.html