C # delegation Summary

Source: Internet
Author: User

1. delegate declaration and compilation principle statement delegation: 1 delegate void Translate (string str); after decompiling, you can copy the following code to private sealed class Translate: System. multicastDelegate // is a multicast delegate {public Translate (object o, Method m) {}// (implementing the delegate Method). The hidden PASSED o is the this object of the current class, the second parameter is the passed-in event public void Invoke (string str) {}// implement the delegate method (pass the parameter to the delegate event) // you can call the delegate service function by calling the new method and call the Invoke () method.} the copy code delegate consists of three parts: 1. Target (pointing to the Method Instance (that is, the Method class), corresponding to the above o) 2. Method (pointing to the Method Type) 3. InvorkList: multicast delegate. An object array during delegation. Each time a method is added, the actual CLR encapsulates it as a delegate and adds it to object. During the call, the "type Pointer" is used to point to the address of the corresponding delegate, and then the Pointer Points down to the next delegate to know that all the delegates in the array have been executed .) 2. Use of delegation 1 // 1. add the delegate 2 tran = new Translate (TranSlateCN) to the method; // create the delegate 3 // tran = TranSlateCN; // The second method for creating the delegate (the effect is the same as above) 4 5 tran. invoke ("Northern Xinjiang"); // Method 6 tran ("Northern Xinjiang") for delegate implementation; // call the delegate event (the above method is implemented) assign a value to the delegate anonymously: AddDel adddemo2 = delegate (int c, int B) {return c + B ;}; 3. delegate role: placeholder: A variable of the delegate type is passed to a method function. Because the method function does not know the method to be executed, but does know the type of the method, a delegate is used as the form parameter, then, the real parameters are defined by the user, as long as they comply with the delegate type. (In fact, it is passed into a form parameter of the delegate type, and different (as long as it complies with the real parameter method of the delegate type) can be passed .) Demo: implement different sorting methods first define the delegate: public delegate int GetMaxDel (object o1, object o2); Define the sorting function: Copy code 1 public object GetMax (object [] objs, getMaxDel maxdel) 2 {3 object maxobj = objs [0]; 4 foreach (var item in objs) 5 {6 if (maxdel (item, maxobj)> 0) 7 {8 maxobj = item; 9} 10} 11 return maxobj; 12} copy the first sort of code: Copy code 1 GetMaxDel maxdel1 = delegate (object o1, object o2) 2 {3 int num1 = Convert. toInt32 (o1); 4 int Num2 = Convert. toInt32 (o2); 5 return num1-num2; 6}; 7 8 object [] objs = {4, 1, 7, 3, 2}; 9 object result = d. getMax (objs, maxdel1); 10 11 Console. writeLine (result. toString (); copy the second sort of code copy code 1 GetMaxDel maxdel2 = delegate (object o1, object o2) 2 {3 Person p1 = o1 as Person; // Person is the class of implementation Definition 4 Person p2 = o2 as Person; 5 if (p1.Age> p2.Age) 6 return 1; 7 else8 return-1; 9 }; copy Code 4. multicast delegate includes a "delegate chain", which is An array of object [] types. After execution, the delegate "type Pointer" (method pointer) will execute the next delegate, and so on, execute and complete all the delegated copy code SayHi sayhi = new SayHi (d. sayHiInChinese); // sayhi = (SayHi) Delegate. combine (sayhi, new SayHi (d. sayHiInEnglish); after decompilation: Therefore, the two delegates are still executed to add sayhi + = d. sayHiInEnglish; sayhi + = d. sayHiInFresh; sayhi ("Hello everyone"); sayhi-= d. sayHiInFresh; // Delegate is called. remove (new Delegate (d. sayHiInFresh); // The following is the SayH that encapsulates the method into a delegate for addition (the same as the method directly added above (compiled into the same code ). I sayhello = new SayHi (d. SayHiInFresh); // Add sayhi + = sayhello to the two delegates. Copy the code. Note: it is best not to return a value for the multicast delegate. If a return value exists, when the multicast delegate is executed, the return value of the multicast delegate is the return value of the last delegate method. 5. Generic delegated generic: constraints: the number type of input parameters and the type of returned values are restricted. There are two types: Return Value generic delegation: Func and non-return generic delegation: action has a returned value for the generic delegate copy code 1 List <int> listInt = new List <int> () {1, 2, 3, 4, 5 }; 2 // generic delegation with returned values. (Most used) 3 // The last outgoing parameter (out type) that can be passed at most (in and out parameters) is of the bool type (determine whether the requirements are met) 4 Func <int, bool> funcdel = a => a> 2; 5 // function prototype: public delegate TResult Func <in T, out TResult> (T arg); essence: it is also a delegate, except that the where method with constraints on the input parameters and return values is 6 7 8 // List (the user filters the where method that meets the generic delegate function in the List) 9 var result = listInt. where (funcdel); 10 foreach (var I in result) 11 {12 Console. writeLine (I); 13} copy the code generic delegate without return values: 1 // The generic delegate Action without return values, rarely use 2 // The delegated Function prototype: public delegate void Action <in T1, in T2> (T1 arg1, T2 arg2); 3 Action <int, int> act = (a, B) => {4 Console. writeLine (a + "+" + B + "+" + (a + B); 5}; 6 act. invoke (2, 3); 6. What is asynchronous Delegation? When the current main thread is executing, define a new thread and execute the corresponding code without affecting the main thread. First: Do not use the callback function to copy code 1 // first (EndInvoke will block the current thread (main thread) 2 // asynchronous delegation: when the main thread is executed, define a new thread to execute code without affecting the main thread running 3 IAsyncResult delResult = newdel. beginInvoke (3, 4, null, null); // the return value is the result of asynchronous delegation 4 while (! DelResult. isCompleted) 5 {6 // when the asynchronous delegate is not completed, the main thread can continue to execute its own code 7} 8 // After the delegate's EndInvoke method is executed, the return value is the parameter method passed in by the delegate. return Value 9 int addResult = newdel. endInvoke (delResult); // blocking the execution of the current thread (until the asynchronous delegate execution is complete) 10 Console. writeLine ("results after thread execution" + addResult); copy the code. Second, use the callback function to define the method for the callback function: copy code 1 // define a method for the callback function (define the method based on the delegate type (void also has the parameter as interface) 2 public static void ForSayCallBack (IAsyncResult iasyResult) 3 {4 // convert the interface type Instance type (as long as it is a class that inherits from this interface, you can convert interface parameters to instance types) (* interface-Oriented Programming *) 5 AsyncResult asyResult = iasyResult as AsyncResult; 6 // AsyncDelegate: obtain the corresponding delegate object (and convert the obtained delegate object to a custom delegate object) 7. myNewdel mydel = asyResult. asyncDelegate as myNewdel; 8 // you can call the EndInvoke method after obtaining your own delegate object. 9 int result = mydel. endInvoke (iasyResult); 10 Console. writeLine ("the asynchronous delegate is executed, the returned result is {0}, and the Thread Id is {1}", result, 11 Thread. currentThread. managedThreadId); 12 // Get the value passed for the callback function (**) 13 int state = (int) iasyResult. asyncState; 14} copy the code to execute asynchronous delegation: 1 newdel. beginInvoke (2, 3, new AsyncCallback (ForSayCallBack), 3); // The last parameter (object Type: multiple values can be passed (for example, one List type )): 2 3 // (**) BeginInvoke internal implementation for the callback function: Step 1: Get a new thread from the thread pool Step 2: use this thread to execute the current delegate (call the delegate of asynchronous delegate). Step 3: Execute callback function 4 Console. writeLine ("the main thread is finished! ");

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.