Delegate and event hidden information

Source: Internet
Author: User

A delegate is a special class that encapsulates the operation objects and specified methods during calls. The constructor of the Delegate. Two parameters, target and methodPtr, are required to specify the object and method of the operation respectively. The call of the delegate uses the Invoke method. The prototype and delegate definition of the method are consistent. The BeginInvoke and EndInvoke methods are also provided for the delegate to support Asynchronization.

The formation of the Delegate chain uses the _ prev field of the Delegate base class MulticastDelegate, [about Delegate and MultiCastDelegate], and uses the Combine and Remove methods to operate the Delegate chain.

To prevent exceptions or blocking of a single delegate in the delegate chain, you can use GetInvocationList () of MulticastDelegate to obtain the delegate clone in the delegate chain to form a delegate array for more control over it.

If you do not specify the prototype of the delegate method, use the delegate. The Delegate. CreateDelegate method is required.

   public class Delegate{public static Delegate CreateDelegate(Type delType, System.Reflection.MemberInfo mi);public static Delegate CreateDelegate(Type delType, Type type, string methodName);public static Delegate CreateDelegate(Type delegateType, object obj, String methodName);public static Delegate CreateDelegate(Type delegateType, object obj, string methodName, Boolean ignoreCase);//......public object DynamicInvoke(object[] args);}

Demo: (call an unknown method prototype by specifying the parameters for generating the delegate object)

namespace DelegateDemo{delegate object TwoInt32(int n1, int n2);delegate object OneString(string s1);class Program{static void Main(string[] args){Delegate d = Delegate.CreateDelegate(typeof(TwoInt32), typeof(Program), "Add");object result = d.DynamicInvoke(1, 2);Console.WriteLine(result);d = Delegate.CreateDelegate(typeof(OneString), typeof(Program), "NumChars");result = d.DynamicInvoke("hello cnblogs!");Console.WriteLine(result);}static object Add(int n1, int n2){return n1 + n2;}static object NumChars(string s1){return s1.Length;}}

Event definition:
Public event EventHandler MyEvent;

The role of an event is to notify the user of the event to perform its custom operations. Concerning event listening and cancellation, it is actually an operation on the delegate chain. The compiler will convert the event into a delegate field and two methods (add _*, remove _ * is used to operate the delegate field ). Event, which I understand is to wrap valid information into an inherited EventArgs object, trigger the event, and notify the event listener to respond to its definition. Three capabilities required for an event: Object Registration event, object cancellation event, object Maintenance Collection of registration objects, and notification. From the perspective of implementation, all these three functions can be done by the delegate chain, and the event is a layer of packaging for the delegate chain. Some bloggers mentioned in the blog that "the relationship between events and delegation is like the relationship between fields and attributes ." This can be seen from the implementation of explicit control event registration:

Explicitly control event registration:

public  delegate void SampleEventHandler(object sender,EventArgs args);private SampleEventHandler sampleEventHandlerDelegate;public  SampleEventHandler Sample{add{sampleEventHandlerDelegate = (SampleEventHandler)Delegate.Combine(sampleEventHandlerDelegate,value);}remove{sampleEventHandlerDelegate=(SampleEventHandler)Delegate.Remove(sampleEventHandlerDelegate,value);}}

The code that explicitly controls event registration clearly shows that it is implemented by declaring a delegate field and defining its accessors. In FCL, The System. Windows. Forms. Control class defines nearly 60 events, which are also used to reduce memory waste. Basic Idea: Let each object save an event/delegate pair set. When a new object is built, the set is empty. When an event is registered, if the collection exists, the delegated instance is merged to the delegated chain. If the delegated instance does not exist, the new event and instance are added to the set.

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.