[C # Basic Knowledge series] Topic 2: Delegate nature

Source: Internet
Author: User
Tags reflector

Introduction:

The previous topic has shared with you why I need to delegate in C #. The topic briefly introduces what delegation is and simple application of delegation, in this topic, we will further introduce the delegation. This topic mainly discusses the nature of the Committee and the delegation chain.

I. Nature of delegation

Usually we can easily use delegation-use C #DelegateDefine delegation with keywords, and then useNewOperator to construct the delegate instance, and then call the callback method by calling the delegate instance (that is, a variable of the delegate object is used to replace the method name. If the contact is hard to understand, here is an example: mydelegate = new mydelegate (obj. mymethod ),MydelegateIs a defined delegate. Assume that there is no parameter defined, and then call the delegate instance -- mydelegate ().The method for calling a delegate is the same as that for calling a method.,If you do not see that mydelegate is a delegate type, you will think that this is a direct call of a method, rather than calling a delegate instance.In this example, you can easily understand this sentence-replace the method name with a delegate object variable, I believe that you will have a better understanding of the Delegate-the delegate is the substitute of the method. The delegate variable is the method name at this time. You can simply understand that the delegate is an "nickname" of the method ".

The previous sections introduced some of the use and understanding of delegation. Now let's take a closer look at how compilers and CLR useDelegateIn the previous topic, I told you that delegation is a class, which is rational, because when we define a delegate type in IDE, the defined code is eventually convertedThe intermediate language Il, and then execute the code in the intermediate language to convert it into the local code. Therefore, the code written in Visual Studio is only a package, real programs execute code in intermediate languages.Now let's look at the intermediate language code that the compiler converts the defined delegate type.

When we define a delegate in the class as follows:

public delegate void DelegateTest(int parm);

The compiler compiles the defined delegate type into the following class:

Public class DelegateTest: System.MulticastDelegate {         public DelegateTest(Object object, IntPtr method);          public virtual Void Invoke(int32 parm);           public virtual IAsyncResult BeginInvoke(Int32 parm, AsyncCallback callback, Object object );            public virtual void EndInvoke(IAsyncResult result);  }

From the code of the intermediate language, we can clearly see that the delegate we write in the Code is a class for the intermediate language, which inherits from the defined in FCLWhen me. multicastdelegate type, all Delegate types are derived from multicastdelegate,This class also defines four methods, oneConstructor,Invoke MethodThere are two asynchronous methods.BegininvokeAndEndinvokeMethod. For the two asynchronous methods, you can view the thread series in my blog. You can useIldasm.exeTool to view the intermediate code generated by the delegate. The following is a screenshot (fromDelegatetestIn front of the icon and our main program passedProgramHoweverProgramIs a class, which is clearly defined as a delegateDelegatetesIs also a class ):

Because all Delegate types are inherited fromMulticastdelegate,MulticastdelegateIt inherits fromDelegate,Therefore, the delegation type inherits the fields, attributes, and methods of multicastdelegate. Among these members, three non-public fields are related to the delegation chain to be introduced in the subsequent topic, so here we first list:

Field

Type

Explanation

_ Target

System. Object

When the delegate object wraps a static method, this field is null. When the delegate object wraps an instance method, this field references the object of the class where the method is located.

_ Methodptr

System. intptr

An internal integer that can be considered as a method handle and identifies the method to be called

_ Invocationlist

System. Object

This field is usually null. A delegate array is referenced only when a delegate chain (Multicast delegate) is constructed. The following section describes the details.

Most people may have such a question: since it is a non-public field, it cannot be seen on msdn. How do I know that there are these three fields? You can useReflectorThe tool is decompiled to view the source code,MulticastdelegateYou can know the namespace and assembly of the class through msdn lookup, so that you can use reflector tool to view the Assembly and namespace.MulticastdelegateClass source code. The following is my useReflectorThe source code shown in this tool:

We can see thatMulticastdelegateThere are only two fields in the class, but _MethodptrAnd _Target field,These two fields are defined inDelegateClass.ReflectorTool to view, here is not specific texture, the article will be given at the endReflectorTool download link.

The delegate object is a package that encapsulates a method and the object to be operated upon when calling this method. For example, when executing the following code:

Public class program {// declare a delegate type. Its instance references a method // This method returns an int parameter and returns void Type Public Delegate void delegatetest (INT parm ); public static void main (string [] ARGs) {// use a static method to instantiate the delegate delegatetest dtstatic = new delegatetest (program. method1); // use the instance method to instantiate the delegate delegatetest dtinstance = new delegatetest (new program (). method2);} Private Static void Method1 (INT parm) {console. writeline ("static method called, parameter value:" + parm);} private void method2 (INT parm) {console. writeline ("instance method called, parameter value:" + parm );}}

In the code, the dtstatic and dtinstance variables reference the initializedDelegatetestDelegate object. The initialization of the three fields listed above the two delegate objects is as follows:

Ii. Summary

In this topic, from the perspective of intermediate language, how can the intermediate language of the defined delegate type converted by the compiler interpret a delegate type? The conclusion is --The delegate is actually a class, Which is derived fromMulticastdelegateClass, and inherits the _ target, _ methodptr and _ invocationlist fields of the class. When we initialize a delegate object, these three fields will be initialized first, for the delegation of the encapsulated instance method and static method, the initialization fields are also different, as shown in the preceding figure, A very important field -- _ invocationlist (the call list of the delegate instance) is referenced here. When a method is encapsulated in the delegate object, this field is null, if the delegate object needs to wrap multiple methods, the _ invocationlist field will be initialized as a referenceDelegate objectArray (that is, a set pointing to the delegate object). The specific content in this area will be detailed in the next topic about the delegate chain. At this point, the content of this topic has ended. We hope that you can further understand the delegation in C.

 

Reflector tool: http://files.cnblogs.com/zhili/Reflector.zip, after reading I think it is helpful, please a lot of recommendations, thank you for your support.

 

 

 

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.