c# - 调用事件,h(args) vs EventName?.Invoke()

标签 c# events

我总是这样调用事件

void onSomeEvent(string someArg) {
    var h = this.EventName;
    if (h != null) {
        h(this, new MyEventArgs(someArg));
    }
}

今天 VS 2015 告诉我这可以简化:

MyEvent?.Invoke(this, new MyEventArgs(someArg));

关于后一种方法的几个问题,我以前没有见过:

  1. 大概是事件名称后的 ? 是检查处理程序是否为空?
  2. 假设处理程序不为空,.Invoke() 看起来很简单
  3. 我已经使用第一个示例多年,并意识到它可以防止竞争条件...大概第二个示例的 ?.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/

相关文章:

c# - 关于 Biztalk 的一般问题

linux - 女士监视器缺少事件,并显示其他多个

jquery - 如何从 Controller 内的事件访问范围?

c# - 对象相等在 .NET 中的行为不同

c# - http 模块 : Request is not available

c# - CB_SELECTSTRING 在某些机器上被忽略

c# - 如何在 MVC 验证属性中使用 Unity IoC?

javascript - Phaser - 不允许多个按键事件

WPF 用户控件事件触发两次

c# - 自定义事件处理程序