Delegated learning notes 1: basic use of delegated learning notes 1

Source: Internet
Author: User

Delegated learning notes 1: basic use of delegated learning notes 1

I. Introduction

Before officially speaking about Delegation, I will first give an example and then introduce the delegation to be discussed later.

It's easy to say hello to a robot.

Code 1.1:

Class Robot {public void GreetByChinese (string name) {Console. WriteLine ("hello," + name + "! ");} Public void GreetByEnglish (string name) {Console. WriteLine (" Hello, "+ name + "! ") ;}// Greet public void DoGreet (string name, string lang) {switch (lang) {case" chinese ": GreetByChinese (name); break; case" english ": greetByEnglish (name); break; default: break; }}} class Program {static void Main (string [] args) {// instantiate the Robot object robot Robot = new Robot (); string name = Console. readLine (); robot. doGreet (name, "chinese"); robot. doGreet (name, "english"); Console. read ();}}View Code

In code list 1.1, a machine human is created. The class encapsulates two greeting methods and a public method that calls these two methods. In the DoGreet method, as long as the conditions in the name and switch are included, a greeting statement can be printed for the corresponding language.

If I want to add other languages, such as French, Japanese, and Korean, I also need to change the case statement in the DoGreet method in addition to the corresponding method, which requires a large amount of maintenance. So what can we do to solve this problem?

One simple method is to directly pass the method as a parameter (variable) to another method (DoGreet) and execute it in it.

But we all know that the object or variable that can be used as a method parameter is of a certain type, and what type is the method? The type corresponding to the method cannot be found. However, there is still a way to indirectly use the method as a parameter, which leads to the "delegate" mentioned below ".

2. Regarding delegation, Microsoft provides the following definitions:

"Delegate is used to pass methods as parameters to other methods ."

As early as C #1.0, we began to support this feature (it should be the most clear if you have used VS2003 ). The definition provided by Microsoft is well understood: We use delegation to pass methods as a parameter (variable) to other methods, other methods are used to execute the actions in this method as a parameter.

3. How can I use delegation?

To use delegation, follow these steps:

1. Define a delegate type

Access modifier delegate return type delegate type name (parameter list );

Ex: public delegate void Greet (string name );

2. Create a method to execute an action (the return type and parameter list must be the same as the delegate type)

Access modifier return type method name (parameter list ){......}

Ex: public void GreetByChinese (string name)

{

Console. WriteLine ("hello," + name + "!");

}

3. instantiate the delegate type

Delegate type name delegate object name = method name;

Ex: Greet greet = GreetByChinese;

4. Start Using and perform operations

Delegate Object Name (parameter list );

Or: Delegate object name. Invoke (parameter list );

Ex: greet ("seasonal tornado"); or: greet. Invoke ("seasonal tornado ");

As shown above, is this simple process. However, some people may say that the method in the definition is not passed as a parameter to another method? Why not? In fact, there is no need to worry about this. We have referenced the method to the greet object in step 3. Since it is an object, it can be used as a method parameter for a long time to solve this problem.

For details, refer to the following code list 3.1:

 

// A common delegate, greeting delegate void Greet (string name); // a machine human, encapsulating greeting class Robot {public void GreetByChiness (string name) {Console. writeLine ("hello," + name + "! ");} Public void GreetByEnglish (string name) {Console. WriteLine (" Hello, "+ name + "! ");} Public void GreetByJapaness (string name) {Console. WriteLine (" your website has been updated successfully, "+ name + "! ") ;}// Greet public void DoGreet (string name, greet) {Greet (name) ;}} class SampleDelegate {static void Main (string [] args) {// instantiate the Robot object robot Robot = new Robot (); string name = Console. readLine (); // greet robot by using the method as a variable. doGreet (name, robot. greetByChiness); robot. doGreet (name, robot. greetByEnglish); robot. doGreet (name, robot. greetByJapaness); Console. read ();}}View Code

 

The execution result is as follows:

 

It is still an example of the host's greeting, but it is more concise to use the Commission? Here, you can easily pass the method as a parameter to the execution method (DoGreet) and execute the operation in it.

Iv. Merge delegation (multi-channel broadcast delegation)

A useful property of a delegate object is that multiple objects can be assigned to a delegate instance using the "+" operator. Multicast delegates include the list of assigned delegates. When a multicast delegate is called, it calls the delegate in the list in sequence. Only delegates of the same type can be merged. The "-" operator can be used to remove a component delegate from a multicast delegate.

In the example of greeting a robot, the DoGreet method is no longer used here, and the "greeting" action is directly carried out in the Main method. As follows (code list 4.1 ):

 

Greet greet = robot.GreetByChiness;greet += robot.GreetByEnglish;greet += robot.GreetByJapaness;greet(name);

 

During running, it will execute the called method in sequence, such:

It is worth noting that the multicast operation can be performed only after the delegate object greet is initialized. For example, the following method is incorrect:

Greet greet + = robot. GreetByChiness;

The removal ("-") operation is similar to the merge operation, but it removes the existing method from the delegate. For example, add the following code after the code in code list 4.1 (code list 4.2 ):

 

Console. WriteLine ("after removing Japanese:"); greet-= robot. GreetByJapaness; greet (name );

 

In the second greet operation, a japanese greeting is missing. The execution result is as follows:

 

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.