C # Use delegation to implement the event notification mechanism. The delegate is equivalent to the c ++ function pointer. The entire process involves a caller, a caller, and a delegate.
-Implementation steps
There are the following steps: 1. Declare the delegate, 2. Define the caller and the called function, 3. Define the caller and the specific implemented function (called function)
1. Declare the delegate, in the package or class, public
Public delegate void PlayGame (Object sender, EventArgs e );
2. Define the caller (like LetsGame) and call the delegate function. There must be a delegate instance in the caller (the caller throws a delegate and is assigned a value to the delegate) Class LetsGame {
Public event PlayGame theGame;
Public void startPlay (EventArgs e ){
If (theGame! = Null ){
TheGame (this, e );
}
}
3. Define the caller (class MS) and specific implemented functions (called functions), that is, the concrete class implementation or function pointer instance. For example, assign a value to the instance entrusted by the caller in. MS in a class called MS. Class MS {
Public MS (LetsGame lg ){
Lg. theGame + = new PlayGame (MSPlayGame );
}
Public void MSPlayGame (Object sender, EventArgs e ){
Console. WriteLine ("Who laughs the last who wins ");
}
}
In this way, when LetsGame. startPlay is called, MS. MSPlayGame is called.
-Practical Application
Comparing the c # GUI event processing or asp.net web control event processing can help us better understand delegation and events. You must be familiar with the following code in asp.net. Private void InitializeComponent ()
{
This. Button1.Click + = new System. EventHandler (this. button#click );
}
Private void button#click (object sender, System. EventArgs e)
{
// Do something
}
This is to implement the event using the delegate. You may find that we didn't declare the delegate object for it and referenced the delegate object through the event keyword, because asp.net has already helped us do this work.
The delegate object is System. EventHandler.
Button1 is equivalent to the LetsGame instance above. It is the caller, and button?click is the call method. When you click
After Button1, Button1 will call button#click.
-Miscellaneous
I think this mechanism is similar to the observer in design pattern. We can use observer to achieve the same effect, but the delegation is more flexible, you do not need to define an interface and all concrete classes implement a method. function pointers (Delegation) are more flexible.
In addition, the Delegate does not have to be used together with the event. The function pointer is used separately.