事件处理程序引发方法约定

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

问题描述

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

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.

这篇关于事件处理程序引发方法约定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)