在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#代码示例
是提升事件的正确方法,
假设Alarm事件,
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.
这篇关于在C#中提出一个事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!