事件处理程序引发方法约定 [英] Event handler raising method convention

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

问题描述

我刚刚浏览并遇到了这个问题:

I was just browsing and came across this question:

动作与委托事件

nobug 的回答包含以下代码:

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

Resharper 在使用创建提升方法"快速修复时也会生成类似的代码.

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);
}

推荐答案

这样更好,因为 Leave 在 null 检查之后但在调用之前变为 null 的可能性很小(这会导致您的抛出 NullReferenceException 的代码).由于委托类型是不可变的,如果您首先将其分配给变量,这种可能性就消失了;您的本地副本不会受到分配后对 Leave 的任何更改的影响.

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天全站免登陆