事件处理程序引发方法约定
问题说明
我刚刚浏览并遇到了这个问题:
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.
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tangefaeg
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
复制文件夹/文件而不修改属性?
it1352 07-15 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20