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.
这篇关于事件处理程序引发方法约定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:事件处理程序引发方法约定
基础教程推荐
- 如何激活MC67中的红灯 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- MS Visual Studio .NET 的替代品 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01