C#6.0添加了这个新的?运算符现在允许调用这样的事件:
someEvent?.Invoke(sender,args);
现在,根据我的阅读,这个运算符保证someEvent被评估一次.
使用这种调用而不是经典模式是否正确:@H_403_6@
var copy = someEvent if(copy != null) copy(sender,args)
我知道certain scenarios以上版本的模式需要额外的锁,但让我们假设最简单的情况.@H_403_6@
解决方法
是
见Null-conditional Operators on MSDN.@H_403_6@
有一个例子涵盖了你的要求@H_403_6@
没有null条件运算符@H_403_6@
var handler = this.PropertyChanged; if (handler != null) handler(…)
使用null条件运算符@H_403_6@
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.@H_403_6@