问题描述
我已经看到了各种编码风格,在C#中触发事件。第一个样式由以下组成:
- 事件处理程序
code> public delegate void NumberReachedEventHandler(object sender,
NumberReachedEventArgs e);
- 事件
public $ Number code public event NumberReachedEventHandler NumberReached;
- 触发事件的方法
protected virtual void OnNumberReached(NumberReachedEventArgs e)
{
if(NumberReached!= null)
{
NumberReached(this,e) ;
}
}
然而,第二种风格有不同的方法来触发事件:
protected virtual void OnNumberReached(NumberReachedEventArgs e)
{
NumberReachedEventHandler handler = NumberReached;
if(handler!= null)
{
handler(this,e);
}
}
对我来说,似乎一种风格检查event为空,第二个样式检查代理是否为空。但是,我的理解是事件只是一个代表的一个实例,所以我想知道是否有任何方式来编写代码。如果是,请说明。提前致谢。
两者都在检查与该事件关联的代理是否为空。
存储到本地的目的是为了防止 - 多线程代码中的风格比赛。
重要的是要注意,使用本地化只能消除两种潜在的种族之一。有关详细信息,请参阅我的2009年有关该主题的文章: a href =http://blogs.msdn.com/b/ericlippert/archive/2009/04/29/events-and-races.aspx =nofollow noreferrer> http://blogs.msdn.com /b/ericlippert/archive/2009/04/29/events-and-races.aspx
以及此问题:
I have seen various coding styles to fire events in C#.The first style consisting of the following:
-an event handler
public delegate void NumberReachedEventHandler(object sender,
NumberReachedEventArgs e);
-an event
public event NumberReachedEventHandler NumberReached;
-and the method to fire the event
protected virtual void OnNumberReached(NumberReachedEventArgs e)
{
if(NumberReached != null)
{
NumberReached(this, e);
}
}
The second style however, has a different method to fire the event:
protected virtual void OnNumberReached(NumberReachedEventArgs e)
{
NumberReachedEventHandler handler = NumberReached;
if(handler != null)
{
handler(this, e);
}
}
To me, it appears that one style checks if the "event" is null and the second style checks if the delegate is null. However, my understanding is that an event is just an instance of a delegate, so I am wondering if there are any advantages to either way of writing the code. If so, please explain. Thanks in advance.
Both are checking to see if the delegate associated with the event is null.
The purpose of storage into the local is to prevent a TOCTOU-style race in multithreaded code.
It is important to note that using a local only eliminates one of two potential races. See my 2009 article on the subject for details: http://blogs.msdn.com/b/ericlippert/archive/2009/04/29/events-and-races.aspx
and also this question:
这篇关于检查处理程序!= null对检查事件!= C null在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!