Null-Conditional Operator 也叫 Null propagating operator 也叫 Safe Navigation Operator
看名字,应该就有点概念了。如果还不知道,提示一下:
有个叫 Conditional Operator 条件运算符(?:)
也就是常会用到的:
- 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 之前的写法:
- var temp = GetCustomer();
- string name = (temp == null) ? null : temp.name;
C# 6.0 的新写法
- var temp = GetCustomer()?.name;
也就是当 GetCustomer() 回传值不为 null 时,取 name 的值给 temp 变量
其他的例子:
- x?.Dispose(); // 当 x 不为 null 时才呼叫 Dispose 方法
例子:
- event EventHandler OnFired;
- void Fire()
- {
- OnFired?.Invoke(this, new EventArgs());
- }
当 OnFired 事件不为 null (有人注册该事件)时,才呼叫 Invoke 方法
例子:
以前的写法:
- public static string Truncate(string value, int length)
- {
- string result = value;
- if (value != null)
- {
- result = value.Substring(0, Math.Min(value.Length, length));
- }
- return result;
- }
新写法: