Can I use null conditional operator instead of classic event raising pattern?

房东的猫 提交于 2019-12-29 01:35:51

问题


C# 6.0 adds this new ?. operator which now allows to invoke events like so:

someEvent?.Invoke(sender, args);

Now, from what I read, this operator guarantees that someEvent is evaluated once. Is it correct to use this kind of invocation instead of the classic pattern:

var copy = someEvent

if(copy != null)
  copy(sender, args)

I'm aware of certain scenarios where above version of pattern would require additional locks, but let's assume the simplest case.


回答1:


Yes

See Null-conditional Operators on MSDN.

There is an example covering what you ask

Without the null conditional operator

var handler = this.PropertyChanged;
if (handler != null)
    handler(…)

With the null conditional operator

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.



来源:https://stackoverflow.com/questions/32734119/can-i-use-null-conditional-operator-instead-of-classic-event-raising-pattern

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!