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

前端 未结 3 1473
长情又很酷
长情又很酷 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:31

    The event has a delegate added to it which "points" to a handler.

    So basically, when the event is raised, the collection of delegates it has, will be invoked, which as result will invoke handlers connected to those delegates.

    //declare delegate
    public delegate void EventHandler(  Object sender,  EventArgs e)
    
    //create event based on delegate
    public event EventHandler evHandler;
    
    //function to attach to handler
    public static void Handler(object sender, EventArgs e) {}
    
    attach eventhandler function through delegate to event.
    event += new EventHandler(Handler);
    

提交回复
热议问题