I believe many of my friends will be confused when I first learned C # About delegation and events. How can I deal with delegation and events? Do you really understand this point! Now, I was confused for several days when I was studying, but it may be because the foundation was not very solid at the time.
I recently read an article about this topic, which is quite well spoken. Now I hope to share and share this knowledge with you. If you have better insights or suggestions, I hope I can share it with my younger brother, increase my knowledge, and promote the friendly exchange atmosphere in the blog garden.
First, to understand the event, you must first start with the delegate
A delegate can be considered as an object that contains an ordered list of methods with the same signature and return value types. That is to say, it defines the type of the method, so that the method can be passed as a parameter of another method. This way of dynamically assigning the method to the parameter makes the program more scalable.
Public delegate void GreetingDelegate (string name); // define a delegate first. Note that the delegate is of type, so the Declaration is the same as that of the type declaration and does not need to be declared inside the class.
Class Program
{
Static void Main (string [] args)
{
GreetingDelegate delegate1; // declares the delegate
Delegate1 = EnglishGreeting; // assign a value to the delegate Type Variable
Delegate1 + = ChineseGreeting; // The delegate is very similar to the String, but the delegate has a special place. You can add multiple values. when calling the delegate, the method goes through www.2cto.com
Sequential call
Delegate1 ("James ")
Console. ReadKey ();
}
Static public void GreetPeople (string name, GreetingDelegate Make)
{
Make (name );
}
Static public void EnglishGreeting (string name) // set
{
Console. WriteLine ("Morning," + name );
}
Static public void ChineseGreeting (string name)
{
Console. WriteLine ("good morning," + name );
}
}
Result: "Morning, James"
"Good morning, James"
From MR. Fans