我总是这样调用事件
void onSomeEvent(string someArg) {
var h = this.EventName;
if (h != null) {
h(this, new MyEventArgs(someArg));
}
}
今天 VS 2015 告诉我这可以简化:
MyEvent?.Invoke(this, new MyEventArgs(someArg));
关于后一种方法的几个问题,我以前没有见过:
- 大概是事件名称后的
?
是检查处理程序是否为空? - 假设处理程序不为空,
.Invoke()
看起来很简单 - 我已经使用第一个示例多年,并意识到它可以防止竞争条件...大概第二个示例的
?.Invoke()
也是如此?
最佳答案
Presumably the ? after the event name is a check if the handler is null?
是的。它是 C# 6 中引入的 null 条件运算符。它在各种方面都很有用。
I've used the first example for years and realize it prevents race conditions... presumably the
?.Invoke()
of the second example does so as well? (see question #1)
是的。基本上,它们是等价的。特别是,它不会对 MyEvent
表达式求值两次。它对其求值一次,然后如果结果不为空,则对其调用 Invoke
。
关于c# - 调用事件,h(args) vs EventName?.Invoke(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37076421/