提高在C#中的事件 [英] Raise an event in C#
问题描述
我碰到这个问题,在Microsoft实践测试来了,我弄糊涂了。这里有一个问题:
I came across this question in a Microsoft Practice Test and I got confused. Here is the question:
这下面的C#代码示例
是引发一个事件,$ B $的正确方法b假设报警事件时,
AlarmEventArgs类和
AlarmEventHandler代表已经
声明?
Which of the following C# code samples is the proper way to raise an event, assuming that the Alarm event, the AlarmEventArgs class, and the AlarmEventHandler delegate have been declared?
下面是他们提供的正确的答案:
Here is the "correct" answer they provided:
AlarmEventArgs e = new AlarmEventArgs(1, 2);
AlarmEventHandler handler = Alarm;
if (handler != null)
{
handler(this, e);
}
不过,也有这似乎是正确的另一个答案。
However, there is also another answer which seems correct.
AlarmEventArgs e = new AlarmEventArgs(1, 2);
if (Alarm!= null)
{
Alarm (this, e);
}
我个人,总是使用第二种方法。它的工作原理就好了。有人能告诉我为什么我应该使用第一种方法,而不是第二个?
I personally, always use the second method. It works just fine. Can someone please tell me why I should use the first method instead of second?
推荐答案
我问过类似的问题。接受的答案是一个很好的解释。
I asked a similar question. The accepted answer is a good explanation.
的 http://stackoverflow.com/questions/282653/checking-for-null-before-event-dispatching-thread-safe
这篇关于提高在C#中的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!