|
-
Jul 2nd, 2007, 08:37 PM
#3
Re: [2.0] Delegates and Events
A delegate is basically as you described: an object that contains a reference to a method. When you invoke the delegate you are executing the method that it references. Normally you would need a reference to the object of which the method was a member in order to execute it. The delegate allows you to pass a method reference around as an object without having to pass the object of which the method is a member. This will become clearer with an example below.
An event is basically a collection of EventHandler delegates. By using the "+=" operator you are adding a delegate to the collection. When an object raises an event what it is doing is basically looping through the collection of delegates for that event and invoking each one. In that way each method that is registered to handle that event will be executed when the event is raised.
Now, consider the situation where you have a form and a button. You declare a method on the form and register it as an event handler for the button's Click event. When the user clicks the button it raises its Click event, thus invoking the EventHandler delegate and executing the method. The button has thus executed a method that is a member of a form that it has no reference to.
All this happens in VB too but the complexity is hidden behind the Handles, AddHandler and RaiseEvent statements.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|