Series 1 describes some scenarios of delegation and events in life. This article describes the meaning of delegation from the perspective of C # language. Let's imagine the following scenario: when the bell rings at noon, you go to the school canteen to queue for meals. Your girlfriend doesn't want to walk and asks you to pack a meal for her. The following code is directly used:
Main (BringLunchEventHandler lunchDelegate = + =
If your girlfriend asks you to bring meals, she just gave you an instruction and you just did what she meant. She tells you what to buy, how much to buy, and where to buy. This is equivalent to specifying a method signature. I don't know if you can better understand it.
BringLunchEventHandler ();
The preceding statement declares a delegate. The delegate and the method are actually very similar: Compared to the method, the delegate has a delegate keyword while there is no method body. <why is the delegate a command, it does nothing>.
LunchDelegate + = Girlfriend. TakeCandy;
If your girlfriend asks you to bring food, you can also buy sugar or something else. In C #, you can use the + = Operator to implement the delegate chain-that is, bind multiple methods to the delegate,
When a delegate is called, the bound methods are executed in sequence. The-= Operator is used to unbind a method.
Additional: A delegate is a type pointing to a method. Similar to the function pointer in C ++, it represents the address of a function. For example, int Is a type, and 2, 3, and 4 are all values of this type. Similarly, delegate is also a type, such as TakeLunch (), DoSomething (int count, String message) is the value of this type, so the delegate type represents a method.
The above is my understanding of delegation. If you have any mistakes, please correct them! The next article explains the relationship between events and delegation in the same way!