[. NET] C # Delegate,
C # Delegate
Http://www.cnblogs.com/liqingwen/p/6046171.html.
Collation
The previous article "C # knowledge Review-delegated delegate" has introduced the basic knowledge of delegation. Here we will provide additional instructions for delegation and further understanding.
Directory
Delegate with naming method and delegate with anonymous method
The delegate can be associated with the naming method. When a delegate is instantiated using a naming method, this method is passed as a parameter, for example:
1 class Program 2 {3 // declare a delegate 4 delegate void MyDel (string message); 5 6 7 static void Main (string [] args) 8 {9 // use the static method as the parameter instantiation delegate 10 MyDel del = Print; 11} 12 13 // declare a method 14 private static void Print (string message) 15 {16 Console. writeLine (message); 17} 18}
This is called the naming method. The delegate constructed using the naming method can encapsulate static methods or instance methods. In earlier versions of C #, naming is the only way to instantiate a delegate. However, if you do not want to pay the system overhead for creating a new method, C # enables you to instantiate the delegate and immediately specify the code block to be processed when the delegate is called. A code block can contain lambda expressions or anonymous methods.
[Note] ① The method passed as the delegate parameter must have the same signature as the delegate declaration. ② The delegated instance can encapsulate static or instance methods. ③ Although the delegate can use the out parameter, we recommend that you do not use it for multi-channel broadcast event delegation because you cannot know which delegate will be called. Example 1: The following is a simple example of declaring and using delegation. Note that the delegate MyDel and the associated method Print have the same signature (even if the parameter names m and n of the method are replaced)
1 class Program 2 {3 // declare a delegate 4 delegate void MyDel (int n, int m); 5 6 static void Main (string [] args) 7 {8 // use the static method Print as the parameter instantiation delegate 9 MyDel del = Print; 10 Console. writeLine ("You are ready. You have to call the delegate! "); 11 12 for (int I = 0; I <10; I ++) 13 {14 Print (I, 1); 15} 16 17 Console. read (); 18} 19 20 // declare a Method 21 private static void Print (int m, int n) 22 {23 Console. write (m-n + ""); 24} 25}
-- Preview version, finishing --