[C #] C # knowledge Review,

Source: Internet
Author: User

[C #] C # knowledge Review,
C # knowledge Review-delegate

[Blogger] Anti-bone Aberdeen [original] http://www.cnblogs.com/liqingwen/p/6031892.html

Directory
  • What's Commission
  • Delegation attributes
  • Use delegate

 

What's Commission

Delegate indicates a reference type for methods with specific parameter lists and return types. When instantiating a delegate, You can associate its instance with any method with a compatible signature and return type. You can call a method by entrusting an instance. Delegate is used to pass methods as parameters to other methods. An event handler is a method called by Delegate. You can create a custom method. When a specific event occurs, a class (such as a Windows Control) can call your method.

The following example demonstrates a delegate statement:

public delegate int Del(int x, int y);

Any method that matches the delegate type in any writable class or structure can be assigned to the delegate. This method can be a static method or an instance method. In this way, you can change the method call programmatically and insert new code into the existing class.

[Note] in the context of method overloading, the method signature does not include the return value. However, in the context of the Delegate, the signature includes the return value. In other words, methods and delegates must have the same return type.

The ability to reference methods as parameters makes delegation an ideal choice for defining callback methods. For example, a reference to a method that compares two objects can be passed as a parameter to the sorting algorithm. Because the comparison code is in a separate process, you can write the Sorting Algorithm in a more common way.

 

Delegation attributes
  • Similar to function pointers in C and C ++, but they are type-safe.

  • Methods can be passed as parameters.

  • It can be used to define callback methods.

  • The delegate can be linked together. For example, multiple methods can be called for an event.

  • The method does not have to match the delegate type completely.

 

Use delegate

Delegation is a type of secure encapsulation method, similar to function pointers in C and C ++. Unlike C function pointers, delegation is object-oriented, type-safe, and reliable. The delegate type is determined by the delegate name.

// This delegate can encapsulate the public delegate void MyDel (string message) method of ", parameter type string, return type void );

 

The delegate object is usually constructed by providing the name of the delegate that encapsulates the method or using an anonymous method. After the delegate is instantiated, the Delegate will pass the method call to it to this method. Parameters passed by the caller to the delegate are passed to the method, and the delegate returns the return value (if any) of the method to the caller. This is called a call delegate. The instantiated delegate can be called by the encapsulated method itself. For example:

1 // The delegate name is MyDel, which can encapsulate method 2 public delegate void MyDel (string message) of "parameter type string and return value type void ); 3 4 class Program 5 {6 static void Main (string [] args) 7 {8 // instantiate delegate 9 MyDel del = Print; 10 // call the delegate 11 del ("Hi"); 12 13 Console. read (); 14} 15 16 /// <summary> 17 // print the text 18 /// </summary> 19 /// <remarks> This is a method that can be used for MyDel delegation </remarks> 20 // <param name = "message"> </param> 21 private static void Print (string message) 22 {23 Console. writeLine (message); 24} 25}

Asynchronous callback is a common method that notifies the caller when a long process is completed. When using a delegate in this way, you do not need to know the implementation method to use the delegate code. The function is similar to the function provided by the encapsulated interface. Another common purpose of callback is to define a custom comparison method and pass the delegate to the short method. It allows the caller's code to become part of the sorting algorithm. The following example uses the Del type as a parameter:

1 class Program 2 {3 static void Main (string [] args) 4 {5 MyDel del = Print; 6 CallbackMethod (100,150, del ); // pass the delegate to the CallbackMethod Method 7 8 Console. read (); 9} 10 11 /// <summary> 12 // callback Method 13 /// </summary> 14 /// <param name = "m"> </param> 15 /// <param name = "n"> </param> 16 // <param name = "del"> </param> 17 private static void CallbackMethod (int m, int n, MyDel del) 18 {19 del (m + n ). toString (); 20} 21 22 private static void Print (string message) 23 {24 Console. writeLine (message); 25} 26}

The delegate does not know the instance type except its encapsulated method. Therefore, the delegate can reference any type of object as long as the object has a method that matches the delegate signature. When the delegate is constructed to encapsulate static methods, the delegate only references methods. Consider the following statement:

1 // This delegate can encapsulate "name MyDel, parameter type string, Return Value Type void" method 2 public delegate void MyDel (string message ); 3 4 class MyClass 5 {6 public void Print1 (string message) 7 {8 Console. writeLine ($ "{message}-{nameof (Print1)}"); 9} 10 11 public void Print2 (string message) 12 {13 Console. writeLine ($ "{message}-{nameof (Print2)}"); 14} 15} 16 17 class Program18 {19 static void Main (string [] args) 20 {21 var myClass = ne W MyClass (); 22 MyDel del1 = myClass. print1; 23 MyDel del2 = myClass. print2; 24 MyDel del3 = Print; 25 26 var del = del1 + del2; 27 del + = del3; // here + = 28 del ("Hi! "); 29 30 Console. read (); 31} 32 33 private static void Print (string message) 34 {35 Console. writeLine ($ "{message}-{nameof (Print)}"); 36} 37}

Multicast. To add other methods to the delegate method list (call list), you only need to use the addition operator or addition assignment operator ("+" or "+ =") to add two delegates.

In this case, the del call list contains three methods: Print1, Print2, and Print. The original three delegates (del1, del2, and del3) remain unchanged. When allMethodsDelegate is called, all three methods are called in order. If the delegate uses the reference parameter, the reference will be passed to all three methods in reverse order, and any changes made by one method will be seen on the other method. When a method triggers an exception that is not caught in the method, the exception is passed to the delegate caller, and subsequent methods in the call list are not called. If the delegate has return values and/or output parameters, it returns the return values and parameters of the last called method. To delete a method from the call list, use the subtraction operator or subtraction assignment operator ("-" or "-= "). For example:

1 static void Main (string [] args) 2 {3 var myClass = new MyClass (); 4 MyDel del1 = myClass. print1; 5 MyDel del2 = myClass. print2; 6 MyDel del3 = Print; 7 8 var del = del1 + del2; 9 del + = del3; // use + = 10 del ("Hi! "); 11 12 Console. writeLine ("====== split line ===="); 13 14 del-= del2; // use-= 15 del ("Hi! "); 16 17 Console. Read (); 18}

1 static void Main (string [] args) 2 {3 var myClass = new MyClass (); 4 MyDel del1 = myClass. print1; 5 MyDel del2 = myClass. print2; 6 MyDel del3 = Print; 7 8 var del = del1 + del2; 9 del + = del3; // use + = 10 // del ("Hi! "); 11 12 var count = del. getInvocationList (). length; // obtain the number of methods in the delegate call list 13 Console. writeLine (count); 14 15 Console. writeLine ("======= split line ======"); 16 17 del-= del2; // use-= 18 // del ("Hi! "); 19 20 count = del. getInvocationList (). length; // obtain the number of methods in the delegate call list 21 Console. writeLine (count); 22 23 Console. read (); 24}

 

[Reference] Microsoft official documentation

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.