Null-conditional Operators
https://msdn.microsoft.com/en-us/library/dn986595.aspx
x?.y – null conditional member access. Returns null if the left hand operand is null.
a?[x] – null conditional indexing. Returns null if the left hand operand is null.
正式在使用VS2015了,安装了配套的Resharper
今天看到绿色的提示,Use null propagation
/// <summary> /// 传感器配置事件(通知DeviceInfo) /// </summary> public event EventHandler<SensorConfigedEventArgs> SensorConfiged; public void OnSensorConfiged(SensorConfigedEventArgs e) { var handler = SensorConfiged; if (handler != null) { handler(this, e); } }
Resharper的优化
var handler = SensorConfiged; handler?.Invoke(this, e);
Used to test for null before performing a member access (?.) or index (?[) operation.
These operators help you write less code to handle null checks, especially for descending into data structures.
int? length = customers?.Length; // null if customers is null Customer first = customers?[0]; // null if customers is null int? count = customers?[0]?.Orders?.Count(); // null if customers, the first customer, or Orders is null
The last example demonstrates that the null-condition operators are short-circuiting.
If one operation in a chain of conditional member access and index operation returns null, then the rest of the chain’s execution stops.
Other operations with lower precedence in the expression continue.
For example, E in the following always executes, and the ?? and == operations execute.
A?.B?.C?[0] ?? E A?.B?.C?[0] == E
Another use for the null-condition member access is invoking delegates in a thread-safe way with much less code. The old way requires code like the following:
var handler = this.PropertyChanged; if (handler != null) handler(…)
The new way is much simpler:
PropertyChanged?.Invoke(e)
The new way is thread-safe because the compiler generates code to evaluate PropertyChanged one time only, keeping the result in temporary variable.
You need to explicitly call the Invoke method because there is no null-conditional delegate invocation syntax PropertyChanged?(e).
There were too many ambiguous parsing situations to allow it.
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2014-11-13 Thread.Start和Delegate.BeginInvoke 以及Control.BeginInvoke
2014-11-13 asp.net和.net的区别
2014-11-13 sqlite的时间筛选字段
2014-11-13 override和new关键字 隐藏父类的方法