Why do we have delegates
Delegates are there for the same reason as we had interfaces in VB6. They ensure that whatever funtion is reference, it will have the signature we require, meaning that we can know at design time what parameters we can pass, although we don't know to what function we will be passing them eventually.
Take multithreading for instance, we need to pass a delegate for ThreadStart, which is a procedure that doesn't take any parameters. Because we need to pass a delegate, it needs to be a procedure with no parameters, the name doesn't matter. Passing any other procedure (with parameters) will result in error.
Delegates & AddressOf Operator
Delegates are used when there is a need for an intermediary between a calling procedure and the procedure being called. The need for an intermediary arises in situations when an object that raises an event should be able to call diffrenet handlers under different circumstances. As the object that raises events cannot know before hand which event handler is handling a specific event, there is a need for an intermediary that can dynamically associate event handlers with events. In .NET, a delegate is used as the intermediary when the AddHandler attaement is used. At runtime, the delegate automatically forwards event calls to the appropriate event handlers.
The AddressOf operator implicitly creates an instance of a delegate. Assume that you create a button called cmdsave and write two event handlers for the click event of the button, cmdsave_click1 and cmd_click2. You can add radio buttons to the form that has the button and decide on the event handler to be called depending on the button selected. To do so, you will write the following code in the form class:
0 comments:
Post a Comment