事件中不需要事件处理程序?

EventHandler Not Needed in Event?

我在使用 Ping class 时注意到了这一点。我最初在实现 PingCompleted 回调方法时遵循了 C# 的文档:

pingSender.PingCompleted += new PingCompletedEventHandler(PingCompletedCallback);

但是,当我向 Timer 的 Elapsed 事件添加新方法时,我注意到我没有传递新的 TimerElapsedEventHandler。相反,我只是按原样传递函数名称:

customTimer.Elapsed += CustomTimerElapsedCallback;

我用 PingCompleted 事件对此进行了测试,它仍然有效:

pingSender.PingCompleted += PingCompletedCallback;

我找不到任何资料可以具体解释这是为什么。谁能解释为什么允许这样做以及 EventHandler 调用的作用?

这是由 C# 编译器为您处理的。这是一个 feature added in C# 2.0 (see section on "How to: Declare, Instantiate, and Use a Delegate").

C# 语言规范第 6.6 节指出:

An implicit conversion (§6.1) exists from a method group (§7.1) to a compatible delegate type. Given a delegate type D and an expression E that is classified as a method group, an implicit conversion exists from E to D if E contains at least one method that is applicable in its normal form (§7.5.3.1) to an argument list constructed by use of the parameter types and modifiers of D

基本上,您可以在代码中使用一个方法的名称(在您的例子中是 "method group",CustomTimerElapsedCallbackPingCompletedCallback),编译器将看到需要委托类型,并放入逻辑来为您进行转换。

pingSender.PingCompleted += PingCompletedCallback;pingSender.PingCompleted += new PingCompletedEventHandler(PingCompletedCallback); 的结果生成的 IL 与结果完全相同。