On C # Delegation

Source: Internet
Author: User

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

. NET provides a mechanism for callback functions through delegation. NET delegates provide many features, such as ensuring that callback methods are type-safe (CLR important goals). A delegate is allowed to call multiple methods (a delegate chain) sequentially, and it supports calling static and instance methods.

The basic syntax of a delegate is not much to say.

InternalDelegatevoid Feedback (IntValue);PublicSealedClassprogram{PublickStaticvoidMain () {}PrivateStaticvoidDelegatedemo () {Counter (1,2,NewFeedback (Writetoconsole)); Program p=Newprogram P (); Counter (1,2,NewFeedback (Writetomsgbox)); }PrivateStaticvoid Counter (int from, int to, Feedback FB) {for (int i= from;i<to;i++if (Fb!=nullprivate static void Writetoconsole (intprivate void Writetomsgbox (int  Val) {MessageBox.Show (val)}}              

and normal call static method instance method no difference, if need callback static method, then Classname.funcname (); If the callback instance method is required, then class_object. FuncName ();

Because a delegate is type-safe, it can call a private method.

Covariance and inverse degeneration.

When you bind a method to a delegate, both C # and the CLR allow reference types for covariance and contravariance, and note that the reference type is OH.

Delegate Object Mycallback (FileStream s);  String SomeMethod (Stream s);      // reference type allows covariance, stream is compliant with contravariant // value type does not allow covariance     

Covariance refers to a method that returns a type derived from the return type of a delegate and cannot be used for void. Contravariance refers to the base class for the parameter type of a delegate that is obtained by the method.

Entrust chain

Delegate.combine (Firstdelegateobj,seconddelegateobj); Firstdelegateobj+=seconddelegateobj;  // syntax sugar effect, equivalent to the previous line 

The code above is constructing a delegate chain.

The principle of a delegate chain is probably: maintain the _invocationlist in the three important non-public fields in the MulticastDelegate class. This field maintains the delegate array.

The other two fields are _target. When a delegate wraps a static method, the field is null. When a delegate object wraps an instance method, this column refers to the object that the callback method is manipulating.

_methodptr an internal integer value that the CLR uses to identify the method to be recalled.

In many cases, the execution of the next method may be affected by the blocking and abnormal effects of one of the methods in the process of executing the delegate chain. At this point, our solution is to use the Getinvocationlist method provided by MulticastDelegate to get an array of delegate references,

Each delegate reference only wants a delegate object in the chain. We can execute every delegate through history.

The delegate chain executes only returns the value returned by the last callback method,

The following is a pseudo-code implementation of the Invoke method in MulticastDelegate, which explains the execution process and principle of the delegate.

Publicint Invoke (IntValue) {IntResult Delegate[] delegateset= _invoctionlistAs delegate[]; if (Delegateset!=null {// delegate chain foreach ( Feedback d in Delegateset) {Result=d (value); }} else {// Call this callback method on the execution object  Result= _methodptr.invoke (_target, Value); // return result;}   

On C # Delegation

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.