C # delegation,

Source: Internet
Author: User

C # delegation,

After reading the 17-Chapter delegate in CLR via C #, I made a simple summary for myself and shared it with the people who need it.

. NET provides a callback function mechanism through delegation.. NET delegation provides many functions, for example, ensuring that the callback method is of type security (important objective of CLR ). Multiple methods (delegated links) can be called sequentially, and static methods and instance methods can be called.

The basic syntax of delegation is not much said.

internal delegate void Feedback(int value);public sealed class Program{      publick static void Main(){      }      private static void DelegateDemo(){            Counter(1,2,new Feedback(WriteToConsole));            Program p=new Program p();            Counter(1,2,new Feedback(WriteToMsgBox));      }      private static void Counter(int from, int to, Feedback fb){             for(int i=from;i<to;i++){                   if(fb!=null)                     fb(i);             }      }      private static void WriteToConsole(int val){             Console.WriteLine(val);      }      private void WriteToMsgBox(int val){               MessageBox.Show(val)      }}

It is no different from the normal call of the Static Method Instance method. If you need to call back the static method, then className. FuncName (); if you need to call back the instance method, then Class_object.FuncName ();

Because the delegate is type-safe, it can call private methods.

Coordination and inverter.

When you bind a method to a delegate, both C # And CLR allow covariant and inversion of the reference type. Note that it is a reference type.

Delegate Object MyCallback (FileStream s); string SomeMethod (Stream s); // The reference type allows covariance. Stream is an inverter int SomeOtherMethod (Stream s ); // covariant is not allowed for value types

Covariance refers to a type that a method can return derived from the Delegate's return type and cannot be used for void. Inversion means that the parameters obtained by the method are the base classes of the delegate parameter type.

Delegated chain

 

Delegate. Combine (FirstDelegateObj, SecondDelegateObj); FirstDelegateObj + = SecondDelegateObj; // syntactic sugar effect, equivalent to the previous line

The above code is to construct the delegate chain.

The principle of the delegated chain is probably to maintain the _ invocationList among the three important non-public fields in the MulticastDelegate class. This field maintains the delegated array.

The other two fields are _ target. this field is null when the delegate wraps a static method. when the delegate object encapsulates an instance method, this field references the object to be operated by the callback method.

_ MethodPtr is an internal integer. CLR uses it to identify the method to be called back.

In many cases, blocking and exceptions of a method may affect the execution of the following methods during the execution of the delegate chain. At this time, our solution is to use the GetInvocationList method provided for us by MulticastDelegate to obtain an array composed of delegate references,

Each delegate reference only needs one delegate object in the chain. We can execute each delegate through traversal.

After the delegate chain is executed, only the values returned by the last callback method are returned,

The pseudocode implementation of the Invoke method in MulticastDelegate is given below. This method explains the execution process and principle of the delegate.

Public int Invoke (int value) {int result; Delegate [] delegateSet = _ invoctionList as Delegate []; if (delegateSet! = Null) {// delegate chain foreach (Feedback d in delegateSet) {result = d (value );}} else {// call this callback Method result = _ methodPtr on the execution object. invoke (_ target, value); // The above code is close to the actual code, but in fact C # cannot indicate it. } Return result ;}

 

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.