我可以使用 null 条件运算符而不是经典的事件引发模式吗?
Can I use null conditional operator instead of classic event raising pattern?
C# 6.0 添加了这个新的 ?.
运算符,它现在允许像这样调用事件:
someEvent?.Invoke(sender, args);
现在,根据我的阅读,此运算符保证对 someEvent 求值一次。
使用这种调用而不是经典模式是否正确:
var copy = someEvent
if(copy != null)
copy(sender, args)
我知道 certain scenarios 以上版本的模式需要额外的锁,但让我们假设最简单的情况。
是
见Null-conditional Operators on MSDN。
有一个例子涵盖了你的问题
没有空条件运算符
var handler = this.PropertyChanged;
if (handler != null)
handler(…)
使用空条件运算符
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.
C# 6.0 添加了这个新的 ?.
运算符,它现在允许像这样调用事件:
someEvent?.Invoke(sender, args);
现在,根据我的阅读,此运算符保证对 someEvent 求值一次。 使用这种调用而不是经典模式是否正确:
var copy = someEvent
if(copy != null)
copy(sender, args)
我知道 certain scenarios 以上版本的模式需要额外的锁,但让我们假设最简单的情况。
是
见Null-conditional Operators on MSDN。
有一个例子涵盖了你的问题
没有空条件运算符
var handler = this.PropertyChanged;
if (handler != null)
handler(…)
使用空条件运算符
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.