Why should events in C# take (sender, EventArgs)?

前端 未结 10 1210
轻奢々
轻奢々 2020-12-08 18:46

It\'s known that you should declare events that take as parameters (object sender, EventArgs args). Why?

相关标签:
10条回答
  • 2020-12-08 19:30

    Because it's a good pattern for any callback mechanism, regardless of language. You want to know who sent the event (the sender) and data that is pertinent to the event (EventArgs).

    0 讨论(0)
  • 2020-12-08 19:35

    "Object sender" allows to reuse one method for multiple objects when the handler method is supposed to do something with the object that raised the event, for example 3 textbox can have one single handler that will reset the text of the firing textbox.

    EventArgs's main advantage is that it allows to refactor event information without the need to change signatures of all handlers in all projects that are subscribed to this kind of event.

    I can't think of a smarter way to deal with events.

    0 讨论(0)
  • 2020-12-08 19:40

    It is a good pattern to use, that way what ever implements the event can find what was sending it.

    Also overriding the EventArgs and passing data through them is the best method. The EventArgs are a base class. If you look at various controls that call events, they have overridden EventArgs which gives you more information about the event.

    Even if you don't need the arguments to do the event, if you do not include them with the first run of the framework and want to add them later, you break all previous implementations, and have to re-write them. Plus if you a creating a framework and going to distribute that it becomes worse because everybody that uses your framework will need to refactor.

    0 讨论(0)
  • 2020-12-08 19:42

    Actually this is debatable whether or not this is the best practice way to do events. There is the school of thought that as events are intended to decouple two segments of code, the fact that the event handler gets the sender, and has to know what type to cast the sender into in order to do anything with it is an anti-pattern.

    0 讨论(0)
提交回复
热议问题