[英]Why does the timer Elapsed need += EventHandler?
I'm following this tutorial to write a Windows Service. 我正在按照本教程编写Windows服务。 Every 60 seconds, a new event is raised that writes to the event log.
每60秒就会引发一个新事件,该事件将写入事件日志。 In the code, the new event is raised using the
+=
operator. 在代码中,使用
+=
运算符引发新事件。
// Set up a timer that triggers every minute.
Timer timer = new Timer();
timer.Interval = 60000; // 60 seconds
timer.Elapsed += new ElapsedEventHandler(this.OnTimer);
timer.Start();
Whats the motivation for using this operator here? 在此使用此运算符的动机是什么? Why is it not just
=
? 为什么不只是
=
? Especially the +
part seems to confuse me.. 尤其是
+
部分似乎使我感到困惑。
Elapsed
is an event. Elapsed
是一个事件。 From ECMA-334 C# Language Specification, chapter 15.8.1 : 根据ECMA-334 C#语言规范的第15.8.1章 :
The only operations that are permitted on an event by code that is outside the type in which that event is declared, are += and -= .
声明事件的类型之外的代码对事件唯一允许的操作是+ =和-=。
Just assignment =
would be a syntax error here. 在这里,仅仅赋值
=
将是语法错误。 And this makes sense, because delegates in C# may have many subscribers. 这是有道理的,因为C#中的委托人可能有许多订户。 From ch.20.1
从ch.20.1起
delegate instance encapsulates an invocation list, which is a list of one or more methods
委托实例封装了一个调用列表,该列表是一个或多个方法的列表
So there are might be several handlers of Elapsed
event, and +=
is just an appending another one. 因此,可能有多个
Elapsed
事件处理程序,而+=
只是追加另一个事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.