Initial Recognition Commission,
Concept of delegation
A delegate is a class that defines the type of a method so that the method can be passed as a parameter of another method. This way, the method is dynamically assigned to the parameter, it can avoid using the If-Else (Switch) statement in a large number in the program, and make the program more scalable. In general, delegation is a type, which is of the same level as the Class.
How to Use DelegationWhen using a delegate, you can treat it like a class. That is, declare the object first, and then instantiate the object. The class is called an object or an instance after instantiation, but the delegate is still called a delegate after instantiation.
A simple example is as follows:
1 using System; 2 using System. collections. generic; 3 using System. linq; 4 using System. text; 5 using System. threading. tasks; 6 7 namespace DelegateDemo 8 {9 // define a delegate 10 public delegate bool Compare (int x, int y); 11 public class PaiXuDemo12 {13 private int [] arry; 14 public int [] Arry15 {16 set {arry = value;} 17 get {return arry;} 18} 19 // 20 larger public bool Greater (int left, int right) 21 {22 retur N left> right; 23} 24 // 25 smaller than public bool Less (int left, int right) 26 {27 return! Greater (left, right); 28} 29 public void Sort (Compare compare) 30 {31 for (int I = 0; I <arry. length-1; I ++) 32 {33 for (int j = I + 1; j <arry. length; j ++) 34 {35 if (compare (arry [I], arry [j]) 36 {37 int tmp = arry [I]; 38 arry [I] = arry [j]; 39 arry [j] = tmp; 40} 41} 42} 43} 44 45 static void Main (string [] args) {46 PaiXuDemo sample = new PaiXuDemo (); 47 sample. arry = GetArry (); 48 // use the descending order of 49 samples. sort (new Compare (sample. less); 50 PrintArry (sample); 51 Console. readKey (); 52} 53 // <summary> 54 // The number is output cyclically 55 // </summary> 56 // <param name = "sample"> </param> 57 private static void PrintArry (PaiXuDemo sample) 58 {59 for (int I = 0; I <sample. arry. length; I ++) 60 {61 Console. writeLine (sample. arry [I]); 62} 63} 64 // <summary> 65 // get the character and length 66 /// </summary> 67 // <returns> </returns> 68 private static int [] GetArry () 69 {70 int [] arry = {12, 14, 15, 16,184, 1, 56,189,652, 2}; 71 return arry; 72} 73} 74}
View Code is as follows: