C # programming guide
Delegate use (C # programming guide)Delegate is a type of secure encapsulation method, which is similar to function pointers in C and C ++. Unlike function pointers in C, delegation is object-oriented, type-safe, and insurance. The delegate type is defined by the delegate name. The following example declares a delegate named Del, which can encapsulate a method that uses strings as parameters and returns void. C # copy the Public Delegate void del (string message) code. When constructing a delegate object, the name of the Delegate-wrapped method is usually provided or the anonymous method is used. After the delegate is instantiated, the Delegate will pass the method calls to it to the method. The parameters passed by the caller to the delegate are passed to the method. The return values (if any) from the method are returned by the delegate to the caller. This is called a call delegate. An instantiated delegate can be called as the wrapped method itself. Example: C # copy the code // create a method for a delegate. publicstaticvoid delegatemethod (string message) {system. console. writeline (Message);} C # copy the code // instantiate the delegate. del handler = delegatemethod; // call the delegate. handler ("Hello World"); the delegate type is derived from.. NET Framework. The delegate type is sealed and cannot be
DelegateIt is impossible to derive a custom class from the delegate type. Because the instantiation delegate is an object, it can be passed as a parameter or assigned to the attribute. In this way, a delegate can be accepted as a parameter and can be called later. This is called asynchronous callback. It is a common method used to notify the caller after a long process is completed. When using a delegate in this way, the code that uses the delegate does not need to know any information about the implementation of the method used. This function is similar to the encapsulation provided by the interface. For more information, see when to use delegation without using interfaces. Another common usage of callback is to define a custom comparison method and pass the delegate to the sorting method. It allows the caller's code to become part of the sorting algorithm. The following example uses the del type as the parameter: C # copy the code publicvoid methodwithcallback (INT param1, int param2, del callback) {callback ("the number is: "+ (param1 + param2 ). tostring ();} Then you can pass the delegate created above to this method: C # copy the code methodwithcallback (1, 2, Handler); In the console, you will receive the following output: the number is: 3 when a delegate is used as an abstract concept, methodwithcallback does not need to directly call the console-you do not need to consider the console when designing it. Methodwithcallback only prepares a string and passes it to other methods. This feature is especially powerful because the delegate method can use any number of parameters. When you construct a delegate to wrap an instance method, the delegate references the instance and method at the same time. In addition to the method it wraps, the Delegate does not know the instance type, so as long as any type of object has a method that matches the delegate signature, the delegate can reference this object. When a delegate is constructed to wrap a static method, it only references the method. Consider the following declaration: C # copy the code publicclass methodclass {publicvoid Method1 (string message) {}publicvoid method2 (string message) {}} and add the preceding static delegatemethod, now we have three methods that can be packaged by del instances. When a delegate is called, it can call multiple methods. This is called multicast. To add additional methods to the delegate method list (call list), you only need to add two delegates using the addition operator or addition assignment operator ("+" or "+ =. Example: C # copy the code methodclass OBJ = new methodclass (); del d1 = obj. method1; del D2 = obj. method2; del D3 = delegatemethod; // both types of assignment are valid. del allmethodsdelegate = D1 + D2; allmethodsdelegate + = D3; at this time, allmethodsdelegate contains three methods in its call list: Method1, method2, and delegatemethod. The original three proxies D1, D2, and D3 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 each of the three methods in sequence, and the changes caused by one method will be visible to the next method. If an exception is thrown for any method but this exception is not caught in the method, the exception is passed to the delegate caller and the method following the call list is no longer called. If the delegate has return values and/or output parameters, it returns the return values and parameters of the last called method. To remove a method from the call list, use the subtraction operator or subtraction assignment operator ("-" or "-= "). For example, C # copy the code // remove method1allmethodsdelegate-= D1; // copy allmethodsdelegate while removing d2del onemethoddelegate = allmethodsdelegate-D2; the delegate type is derived from
System. DelegateTherefore, you can call the methods and attributes defined by this class on the delegate. For example, to find the number of methods in the delegate call list, you can write the following code: C # copy the code int invocationcount = d1.getinvocationlist (). getlength (0); the delegate with multiple methods in the call list is derived from multicastdelegate, which is
System. Delegate. Because both classes support
GetinvocationlistSo the above Code applies in both cases. Multicast delegation is widely used in event processing. The event source object sends event notifications to the receiver object that has registered to receive the event. To register an event, the receiver creates a method to handle the event, creates a delegate for the method, and passes the delegate to the event source. When an event occurs, the source calls the delegate. Then, delegate the call to the receiver's event processing method and send event data. The delegate type of a given event is defined by the event source. For more information, see events (C # programming guide ). During compilation, comparing two different types of delegation assigned will generate a compilation error. If the delegated instance belongs to the type statically
System. Delegate. Example: C # copy the code delegate void delegate1 (); Delegate void delegate2 (); staticvoid method (delegate1 D, delegate2 E, system. delegate f) {// compile-time error. // console. writeline (D = E); // OK at compile-time. false if the run-time type of f // is not the same as that of D. system. console. writeline (D = f);} (Source: msdn)