1. Why use a delegate
Because of the three methods, only one line of code is different. Consider simplifying the three methods to one and passing the different parts as parameters into the above method. Pass a method as an argument to another method, passing the type of the method, and defining the bit delegate type.
2. Delegation concept
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceDelegate Concept {classProgram {//when a method is used as a parameter to another method, the preceding method can use the delegate//the definition of a delegate should be consistent with the label of its corresponding function//function label, which refers to the function's return value and parameters Public Delegate voidDele (stringname); Static voidMain (string[] args) { //1.1 initializes the delegate and calls directly//Dele Dele = new Dele (Sayhichinese); //dele ("Meow"); //1.2 initializing a delegate//Dele Dele = Sayhichinese; //dele ("Meow"); //1.3 Initializing delegates with anonymous functions//Dele Dele = Delegate (string name)//{ //Console.WriteLine ("Anonymous" + name); //}; //dele ("Meow"); //2. Delegate as a parameter to another method//Test ("Cat", Sayhichinese); //3. Initializing delegates with anonymous functions//you can avoid declaring multiple functions for when a function is used only once//Test ("Dog", delegate (string name)//{ //Console.WriteLine ("AnonyMouse" + name); //Console.readkey (); //}); //4. Lamda Expressions (= = goes to) and delegatesDele Dele = (stringName) = = {Console.WriteLine ("Lamda-expression"+name); }; Dele ("Cat"); } Public Static voidTest (stringname, Dele Dele) {dele (name); } Public Static voidSayhichinese (stringname) {Console.WriteLine ("how you doing?"+name); Console.readkey (); } Public Static voidSayhienglish (stringname) {Console.WriteLine ("How is it ?"+name); Console.readkey (); } }}
C # Delegate