事件处理方法,提高会议 [英] Event handler raising method convention
问题描述
我只是浏览并在这个问题就来了:
的从nobug 包含这些代码答案:
受保护的虚拟无效OnLeave(EmployeeEventArgsË ){
VAR处理器=假;
如果(处理!= NULL)
处理器(这一点,E);
}
ReSharper的也使用了创建养法速战速决时,会产生类似的代码
我的问题是,为什么这行必要的:
VAR处理器=假;
为什么它比写这个?
受保护的虚拟无效OnLeave(EmployeeEventArgs E){
如果(离开!= NULL)
离开(这一点,E);
}
这是更好,因为有一个微小的可能性,即离开
成为空检查之后null,但调用(这将导致你的代码抛出之前的NullReferenceException
)。由于委托类型是不可变的,如果你第一次把它分配给一个变量这种可能性消失;您的本地副本将不会被转让后的任何修改离开
受到影响。
请注意,虽然这种做法也造成相反的一个问题;这意味着有一个(微小的,但现有的)可能性的事件处理程序被调用的它已被从事件的拆卸之后。这种情形当然要处理的优雅以及。
I was just browsing and came across this question:
The answer from nobug included this code:
protected virtual void OnLeave(EmployeeEventArgs e) {
var handler = Leave;
if (handler != null)
handler(this, e);
}
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);
}
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屋!