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.
这篇关于事件处理程序引发方法约定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:事件处理程序引发方法约定
基础教程推荐
- WPF 模态进度窗口 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
