我可以使用空条件运算符而不是经典事件提升模式吗? [英] Can I use null conditional operator instead of classic event raising pattern?
问题描述
C#6.0添加了这个新的?。
运算符,现在允许调用如下事件:
C# 6.0 adds this new ?.
operator which now allows to invoke events like so:
someEvent?.Invoke(sender, args);
现在,从我读到的,这个运算符保证someEvent被评估一次。
使用这种调用而不是经典模式是正确的:
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)
我知道某些场景,其中上述版本的模式将需要额外的锁,但让我们假设最简单的情况。 / p>
I'm aware of certain scenarios where above version of pattern would require additional locks, but let's assume the simplest case.
推荐答案
是
请参阅 MSDN上的无条件运算符 。
有一个例子涵盖你所要求的
There is an example covering what you ask
没有空条件运算符
var handler = this.PropertyChanged;
if (handler != null)
handler(…)
null条件运算符
PropertyChanged?.Invoke(e)
新的方法是线程安全的,因为编译器生成代码来一次性评估PropertyChanged,并将结果保留在临时变量中。
The new way is thread-safe because the compiler generates code to evaluate PropertyChanged one time only, keeping the result in temporary variable.
这篇关于我可以使用空条件运算符而不是经典事件提升模式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!