Delegation and events-chat series (2)

Source: Internet
Author: User

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!

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.