声明事件的传统方法是通过从 EventArgs 扩展来创建自定义 args 类:
public class SomethingHappenedEventArgs : EventArgs
然后将其和对声明事件的对象的引用放入处理程序中:
public SomethingHappenedHandler(object sender, SomethingHappenedEventArgs e)
但是,当然,您不必这样做。您的事件处理程序 delete 可以具有您喜欢的任何方法签名。
那么,“object, EventArgs”签名只是约定俗成吗?它过时了吗?还是它有我不理解的明显技术优势?
最佳答案
这是惯例。
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/