c# - "object sender, EventArgs e"事件处理程序签名只是一个约定吗?

标签 c# events

声明事件的传统方法是通过从 EventArgs 扩展来创建自定义 args 类:

public class SomethingHappenedEventArgs : EventArgs 

然后将其和对声明事件的对象的引用放入处理程序中:

public SomethingHappenedHandler(object sender, SomethingHappenedEventArgs e)

但是,当然,您不必这样做。您的事件处理程序 delete 可以具有您喜欢的任何方法签名。

那么,“object, EventArgs”签名只是约定俗成吗?它过时了吗?还是它有我不理解的明显技术优势?

最佳答案

这是惯例。

Events Tutorial (C#)

Although the C# language allows events to use any delegate type, the .NET Framework has some stricter guidelines on the delegate types that should be used for events.
The .NET Framework guidelines indicate that the delegate type used for an event should take two parameters, an "object source" parameter indicating the source of the event, and an "e" parameter that encapsulates any additional information about the event. The type of the "e" parameter should derive from the EventArgs class. For events that do not use any additional information, the .NET Framework has already defined an appropriate delegate type: EventHandler.

Events, Delegates, and CLR Event System Conventions

By convention, event delegates in the .NET Framework have two parameters, the source that raised the event, represented by the sender parameter, and the data for the event, represented by the e parameter.

它没有过时。

Handling and Raising Events (.NET Framework 4.6 and 4.5)

The EventArgs class is the base type for all event data classes. EventArgs is also the class you use when an event does not have any data associated with it. When you create an event that is only meant to notify other classes that something happened and does not need to pass any data, include the EventArgs class as the second parameter in the delegate. You can pass the EventArgs.Empty value when no data is provided. The EventHandler delegate includes the EventArgs class as a parameter.

关于c# - "object sender, EventArgs e"事件处理程序签名只是一个约定吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33135607/

相关文章:

java - 如何处理 Java 中的关闭应用程序事件?

javascript - 单击事件并移动鼠标

android - 在 Android 中设置从另一个线程或 BeginInvoke 可见的 TextView

C#方法,使用refs和outs修改变量

c# - 使用 ASP.NET 样板将 ValueObject 存储在数据库中

c# - 具有检查元素功能的 HTML 渲染?如何使用 C#

c# - 图像配准 - 使用 AForge.NET 框架的相位相关算法 (C#)

c# - 如何解决使用 Visual Studio 将 C# 项目部署到 AX 2012 时出现的错误?

events - ColdFusion 点击​​事件?

powershell - 将参数传递给Register-EngineEvent操作脚本 block