事件处理方法,提高会议 [英] Event handler raising method convention

查看:143
本文介绍了事件处理方法,提高会议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是浏览并在这个问题就来了:



动作VS委托事件



从nobug 包含这些代码答案:

 受保护的虚拟无效OnLeave(EmployeeEventArgsË ){
VAR处理器=假;
如果(处理!= NULL)
处理器(这一点,E);
}



ReSharper的也使用了创建养法速战速决时,会产生类似的代码



我的问题是,为什么这行必要的:

  VAR处理器=假; 



为什么它比写这个?



 受保护的虚拟无效OnLeave(EmployeeEventArgs E){
如果(离开!= NULL)
离开(这一点,E);
}


解决方案

这是更好,因为有一个微小的可能性,即离开成为空检查之后null,但调用(这将导致你的代码抛出之前的NullReferenceException )。由于委托类型是不可变的,如果你第一次把它分配给一个变​​量这种可能性消失;您的本地副本将不会被转让后的任何修改离开受到影响。



请注意,虽然这种做法也造成相反的一个问题;这意味着有一个(微小的,但现有的)可能性的事件处理程序被调用的它已被从事件的拆卸之后。这种情形当然要处理的优雅以及。


I was just browsing and came across this question:

Action vs delegate event

The answer from nobug included this code:

protected virtual void OnLeave(EmployeeEventArgs e) {
  var handler = Leave;
  if (handler != null)
    handler(this, e);
}

Resharper also generates similar code when using the "create raising method" quick-fix.

My question is, why is this line necessary?:

var handler = Leave;

Why is it better than writing this?:

protected virtual void OnLeave(EmployeeEventArgs e) {
  if (Leave != null)
    Leave(this, e);
}

解决方案

It's better because there is a tiny possibility that Leave becomes null after the null check, but before the invocation (which would cause your code to throw a NullReferenceException). Since the delegate type is immutable, if you first assign it to a variable this possibility goes away; your local copy will not be affected by any changes to Leave after the assignment.

Note though that this approach also creates a issue in reverse; it means that there is a (tiny, but existing) possibility that an event handler gets invoked after it has been detached from the event. This scenario should of course be handled gracefully as well.

这篇关于事件处理方法,提高会议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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