Delegate (1): Delegate and method, delegate Method

Source: Internet
Author: User

Delegate (1): Delegate and method, delegate Method



1. Use delegate to take methods as method parameters



Let's take a look at a small example:


Namespace delegate Example 2 {/******* delegate Example 1 * Note: This program mainly uses the delegate as a method parameter to pass in the method, assign a value to the method as needed. ** Key point: Use the delegate to use the method as the method parameter ********* // definition of the delegate // 1. Delegate: the position of the delegate is the same as that of the string, so GreetingDelegate should also be a type, but the Declaration method and class of the delegate are completely different. // 2. The delegate is indeed compiled into a class during compilation. Because delegate is a class, you can declare the delegate in any place where the class can be lifecycle. Public delegate void GreetingDelegate (string name); class Program {static void Main (string [] args) {GreetPeople ("", EnglishGreeting); GreetPeople ("vac ", chineseGreeting); Console. readKey () ;}# region does not define the "hello" Method for calling the delegate method. //// <summary> //// the method used to send greetings to someone, when passing the name parameter representing someone's name, such as jimmy, In this method, the EnglishGreeting method will be called and the name parameter will be passed again. Ehglish is used to output good to the screen, morning, jimmy //// </summary> //// <param name = "na Me "> </param> // public void GreetPeople (string name, Language lang) // {// do some additional things, such as initialization, // switch (lang) // {// case Language is omitted here. english: // EnglishGreeting (name); // break; // case Language. chinese: // ChineseGreeting (name); // break; //} // EnglishGreeting (name ); ///} # endregion # region uses a delegate to call the greeting method // After the delegate is used, the public static void GreetPeople (string name, GreetingDele Gate MakeGreeting) {MakeGreeting (name );} # endregion // <summary> // Method for speaking good morning in English /// </summary> // <param name = "name"> </param>/ // <returns> </returns> public static void EnglishGreeting (string name) {Console. writeLine ("good, morning! "+ Name );} /// <summary> /// method of greeting in Chinese /// </summary> /// <param name = "name"> </param> /// <returns> </returns> public static void ChineseGreeting (string name) {Console. writeLine ("good morning, baby ~~~ "+ Name) ;}# after region has been delegated, it does not need to be enumerated. // <summary> /// defines an enumeration, used to determine which version of Greeting method is suitable // </summary> // public enum Language // {// English, Chinese //} # endregion }}






When there is no delegate, we need to define an enumeration, write the English and Chinese changes, and then call the GreetPeople method, we need to make a choice through swich, but this can only cope with the temporary balance. When there is a change, such as adding a Japanese welcoming method, we have to go back and change the switch method.


In the object-oriented design philosophy, we have used many design patterns to remove selection and respond to changes, such as factories, status patterns, and command patterns. However, if we use delegation, we can treat the method as a variable, so that the process becomes very simple, and the overall structure is much easier than adding a design pattern.





2. Bind the method to the Delegate


First, let's look at the example:


Namespace binds the method to the delegate example {// definition of the delegate // 1. Delegate: The delegate appears at the same position as the string, so GreetingDelegate should also be of the same type, however, the delegate declaration method and class are completely different. // 2. The delegate is indeed compiled into a class during compilation. Because delegate is a class, you can declare the delegate in any place where the class can be lifecycle. Public delegate void GreetingDelegate (string name); class Program {static void Main (string [] args) {// since the same type as the string type is delegated to GreetingDelegate, a parameter type is defined, then, can I use the delegate as follows ...... // So, try the following call // Note: 1. "=" is the syntax of the value assignment; "+ =" is the syntax of the binding ;//....... 2. If "+ =" is used for the first time, an unassigned local variable compilation error will occur. # region uses the delegate as the variable // as the following, we pass the delegate as a variable // GreetingDelegate delegate1, delegate2; // delegate1 = EnglishGreeting; // delegate2 = ChineseGreeting; // GreetPeople ("", delegate1 ); // GreetPeople ("vac", delegate2); // Console. readKey (); # endregion # region delegate carrying method example // GreetingDelegate delegate1; // delegate1 = EnglishGreeting ;/ /Assign a value to the delegate type variable first // delegate1 + = ChineseGreeting; // bind another method to this delegate variable // call the EnglishGreeting and ChineseGreeting Methods successively // GreetPeople ("", delegate1 ); // The output name is "paddy field as elegant" // Console. readKey (); # endregion # region calls the method directly through delegation // GreetingDelegate delegate1; // delegate1 = EnglishGreeting; // value assignment of the delegate variable // delegate1 + = ChineseGreeting; // bind a method to the delegate. // two methods will be called successively. // delegate1 ("paddy field (vac)"); // Console. readKey (); # endregion # regi On simplify delegate calls // GreetingDelegate delegate1 = new GreetingDelegate (EnglishGreeting); // delegate definition and assignment // delegate1 + = ChineseGreeting; // binding method # endregion # example of region unbinding a delegate // GreetingDelegate delegate1 = new GreetingDelegate (EnglishGreeting); // delegate1 + = ChineseGreeting; // bind the delegate to the delegate. // call EnglishGreeting and ChineseGreeting successively. // GreetPeople ("This is the first call", delegate1); // Console. writeLine (); // cancel the EnglishGreeting call // deleg Ate1-= EnglishGreeting; // cancel the second call to EnglishGreeting // call again // GreetPeople ("the second call to the method. Note that several methods have been called ...... ", Delegate1); // Console. readKey (); # endregion} # region uses a delegate to call the method in the hello way // After the delegate is used, the public static void GreetPeople (string name, greetingDelegate MakeGreeting) {MakeGreeting (name );} # endregion // <summary> // Method for speaking good morning in English /// </summary> // <param name = "name"> </param>/ // <returns> </returns> public static void EnglishGreeting (string name) {Console. writeLine ("good, morning! "+ Name );} /// <summary> /// method of greeting in Chinese /// </summary> /// <param name = "name"> </param> /// <returns> </returns> public static void ChineseGreeting (string name) {Console. writeLine ("good morning, baby ~~~ "+ Name );}}}



The following summarizes the delegate call process:


1. All delegate calls are assigned values first, and then carry other methods.

2. The delegate can carry methods or unload the methods.



After the delegate is used, we can simplify the call and flexibly select the called method when using it, delegation can replace the flexibility of the previous interface or implementation class in implementing method calling by using polymorphism in the structure, and simplify the calling method to a certain extent.




Not complete ..........
















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.