C # keywords: Delegate and event (delegation and event) [msdn original excerpt] [1]

Source: Internet
Author: User
A delegate is a type that safely encapsulates a method, similar to a function pointer in C and C ++. unlike C function pointers, delegates are object-oriented, type safe, and secure. the type of a delegate is defined by the name of the delegate. the following example declares a delegate named del that can encapsulate a method that takes a string as an argument and returns void:
(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 .)
public delegate void Del(string message);
A delegate object is normally constructed by providing the name of the method the delegate will wrap, or with an anonymous method. Once a delegate is
Instantiated, a method call made to the Delegate will be passed by the delegate to that method. the parameters passed to the delegate by the caller are passed to the method, and the return value, if any, from the method is returned to the caller by the delegate. this is known as invoking the delegate. an instantiated delegate can be invoked as if it were the wrapped method itself. for example :( construct a delegate The name of the method to be wrapped or the anonymous method is usually provided by the delegate. 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 :)
// Create a method for a delegate.public static void DelegateMethod(string message){    System.Console.WriteLine(message);}
// Instantiate the delegate.Del handler = DelegateMethod;// Call the delegate.handler("Hello World");
Delegate types are derived from the delegate class in. net Framework. delegate types are sealed-they cannot be derived from-and it is not possible to derive custom classes from delegate. because the instantiated delegate is an object, it can be passed as a parameter, or assigned to a property. this allows a method to accept a delegate as a parameter, and call the delegate at some later time. t His is known as an asynchronous callback, and is a common method of policying a caller when a long process has completed. when a delegate is used in this fashion, the code using the delegate does not need any knowledge of the implementation of the method being used. the functionality is similar to the encapsulation interfaces provide. for more information, see when to use delegates instead of inte Rfaces. another common use of callbacks is defining a custom comparison method and passing that delegate to a sort method. it allows the caller's code to become part of the sort algorithm. the following example method uses the del type as a parameter :( the delegate type is derived from.. NET Framework. The delegate type is sealed and cannot be derived from delegate or custom classes. 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 :)
public void MethodWithCallback(int param1, int param2, Del callback){    callback("The number is: " + (param1 + param2).ToString());}
Methodwithcallback (1, 2, Handler); // (PS: Pay attention to callback usage)

----------------------- Split line -------------------------------------

 

When a delegate is constructed to wrap an instance method, the delegate references both the instance and the method. A delegate has no knowledge of the Instance type aside from the method it wraps, so a delegate can refer to any type of object as long as there is a method on that object that matches the delegate signature. when a delegate is constructed to wrap a static method, it only references t He method. Consider the following declarations :( when the delegate is constructed as a wrap instance method, the Delegate will reference both the instance and method. 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 statement :)
public class MethodClass{    public void Method1(string message) { }    public void Method2(string message) { }}
Along with the static delegatemethod shown previusly, we now have three methods that can be wrapped by a del instance. A delegate can call more than one method when invoked. this is referred to as multicasting. to add an extra Method to the Delegate's list of methods-the invocation list-simply requires adding two delegates using the addition or addition assignment operators ('+' or '+ = '). for examp Le: (add the static delegatemethod shown above. Now we have three methods for packaging 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 :)
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 point allmethodsdelegate contains three methods in its invocation list-Method1, method2, and delegatemethod. The original three delegates, D1, D2,
And D3, remain unchanged. when allmethodsdelegate is invoked, all three methods are called in order. if the delegate uses reference parameters, the reference is passed sequentially to each of the three methods in turn, and any changes by one method are visible to the next method. when any of the methods throws an exception that is not caught within the method, that exception is passed to the caller Of the delegate and no subsequent methods in the invocation list are called. if the delegate has a return value and/or out parameters, it returns the return value and parameters of the last method invoked. to remove a method from the invocation list, use the decrement or decrement assignment operator ('-' or '-= '). for example :( in this case, allmethodsdelegate contains three methods in its call list: Method1, method2, and delegatemeth. OD. 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:
//remove Method1allMethodsDelegate -= d1;// copy AllMethodsDelegate while removing d2Del oneMethodDelegate = allMethodsDelegate - d2;
Because Delegate types are derived from system. delegate, the methods and properties defined by that class can be called on the delegate. for example, to find the number of methods in a delegate's invocation list, you may write :( because the delegate type is derived from system. delegate, so 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 :)
int invocationCount = d1.GetInvocationList().GetLength(0);
Delegates with more than one method in their invocation list derive from multicastdelegate, which is a subclass of system. Delegate. The above code works in either
Case because both classes support getinvocationlist. multicast delegates are used extensively in event handling. Event source objects send Event Notifications to recipient objects that have registered to receive that
Event. to register for an event, the recipient creates a method designed to handle the event, then creates a delegate for that method and passes the delegate to the event source. the source callthe delegate when the event occurs. the delegate then callthe event handling method on the recipient, delivering the event data. the delegate type for a given event is defined by the event source. for more, see events (C # programming guide ). comparing delegates of two different types assigned at compile-time will result in a compilation error. if the delegate instances are statically of the type system.
Delegate, then the comparison is allowed, but will return false at run time. For example :( the delegate with multiple methods in the call list is derived from multicastdelegate, which is a subclass of system. Delegate. Because both classes support getinvocationlist, 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 system. Delegate statically, comparison is allowed, but false is returned at runtime. Example :)
delegate void Delegate1();delegate void Delegate2();static void 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);}

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.