调用事件,H(参数)与事件名称?.Invoke() [英] Invoking Events, h(args) vs EventName?.Invoke()

查看:751
本文介绍了调用事件,H(参数)与事件名称?.Invoke()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我总是调用事件等等

 无效onSomeEvent(字符串someArg){
VAR H =本.EventName;
如果(H!= NULL){
H(这一点,新MyEventArgs(someArg));
}
}

今天VS 2015告诉我这可以简化为:< ?/ p>

  MyEvent .Invoke(这一点,新MyEventArgs(someArg)); 

在这后一种方法,我从来没见过几个问题:




  1. 想必
  2. 假设处理不为空, .Invoke()似乎足够直截了当

  3. 我用的第一个例子多年,并意识到它防止竞争条件......想必?第二个例子中的调用()这样做呢?


解决方案

想必?事件名称后检查,如果处理程序为null?




是的。这是空有条件的经营者,在C#6,它在各种方式有用的介绍。




我用的第一个例子多年并实现它可以防止竞争条件......想必?第二个例子中的调用()这样做呢? (见问题#1)




是的。基本上,他们是等价的。特别是,它的的评估两次 MyEvent 的表达。它计算它一次,然后如果结果非空,它调用调用就可以了。


I've always invoked events as so

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

Today VS 2015 tells me this can be simplified:

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

A few questions on this latter method, which I've not seen before:

  1. Presumably the ? after the event name is a check if the handler is null?
  2. Assuming the handler is not null, .Invoke() seems straightforward enough
  3. 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?

解决方案

Presumably the ? after the event name is a check if the handler is null?

Yes. It's the null conditional operator, introduced in C# 6. It's useful in all kinds of ways.

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)

Yes. Basically, they're equivalent. In particular, it does not evaluate the MyEvent expression twice. It evaluates it once, and then if the result is non-null, it calls Invoke on it.

这篇关于调用事件,H(参数)与事件名称?.Invoke()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆