As jimmyzhang said: it is not easy for many people who have been in contact with C # for a long time to better understand delegation and events. They are like a hacker. People who have passed the hacker think it is too easy, and people who have never seen the delegate and event will feel different (bi) panic and uncomfortable.
Summary:
(1) When a class is delegated, it defines the type of the method so that the method can be passed as a parameter of another method. This dynamic method is paid to the parameter, it can avoid using a large number of statements such as if --- else switch in the program, and make the program highly scalable.
(2) delegate can be used to bind multiple methods to the same delegate variable. When this variable is called, all the bound methods can be called in sequence.
(3) There is nothing difficult to understand about an event. Declaring an event is similar to declaring an encapsulated delegate type variable.
Below is a simple example. Let's take a look:Don't think you can understand it after reading it. Do it yourself..
Public delegate void wenhaodelegate (string name );
Public class wenhao
{
Public event wenhaodelegate delegate1;
Public void iwenhao (string name)
{
If (delegate1! = Null) // if there is a method to register with the delegate variable
{
Delegate1 (name); // call the method by Delegate
}
}
}
Class Program
{
Public static void english (string name)
{
Console. WriteLine ("morning:" + name );
}
Public static void chinese (string name)
{
Console. WriteLine ("Good morning:" + name );
Console. Read ();
}
Static void Main (string [] args)
{
Wenhao mywenhao = new wenhao ();
Mywenhao. delegate1 + = english;
Mywenhao. delegate1 + = chinese;
Mywenhao. iwenhao ("Duan Yingjie ");
}
}