What is the difference between a delegate type and eventhandler type?

前端 未结 3 1482
长情又很酷
长情又很酷 2021-02-09 05:48

Three related idioms: event, delegate, event-handler. I always get confused by who is \"added\" to who.

event += handler
event += delegate
handler += delegate
         


        
3条回答
  •  不思量自难忘°
    2021-02-09 06:16

    An "event" is really just shortcut for two methods that work with a delegate - the add and remove accessors. The compiler, by default, makes a delegate behind the event (if you don't write your own accessors).

    When you call someEvent += aDelegate;, you're calling the event's add accessor. Normally, this is translated by the compiler into a delegate += call for a delegate with the same signature as the event - similar to how automatic properties automatically map to a backing field. This is why an event seems so similar to a delegate.

    what confuses me more is this signature in MSDN: public delegate void EventHandler( Object sender, EventArgs e)

    This signature is just a delegate signature. An event can, technically, use any delegate. However, by convention, it will always take two parameters - the first is the "sender" that raised the event, the second is a class that derives from EventArgs (like EventHandler and EventHandler).

提交回复
热议问题