The delegation of C # advanced programming

Source: Internet
Author: User

See C # Advanced Programming version Eighth see the delegation, some people say it is similar to the agent in Java, but I think this is a C # and other programming languages different places, this should also be important, otherwise the book will not be a large part of the concept of delegation and application. I looked at the information on the Commission on the Internet, found that they are like a sill, passed the threshold of the people, it is really easy, and no past people every time to see the Commission and events feel in the heart to panic, mixed with uncomfortable.


The first question I had in mind when I first saw the word "commissioned" was:

1. What is a delegate?


I see the whole chapter, is still smattering, Kung Fu, through a strong network, I find the answer, what is the commission it?

A delegate is the ability to pass a method as a parameter, which means that the delegate can manipulate the method parameter as if it were a variable. See here I found that this is not the concept of C # First, because in C + + has the concept of function pointers and applications, I understand this is actually Microsoft's C + + function pointer as a prototype derived from, after the encapsulation of such a special concept, in fact, I do not seem very special, after all, in C + + I have learned it in the past.



Now that I know the concept of a delegate, my second question comes again.

2. How does this delegate work?

I think how to use, or to take the demo to explain it will be more convenient to understand and contrast. The following is the code that I see for the great gods on the web, and we don't discuss the actual meaning of the code given to the demo, just to make it easier for the reader to understand what is called a delegate. The code is as follows:


A. Now, say hello to someone. Then we need to know his name. The method is as follows:

public static void Chinesegreeting (string name) {Console.WriteLine ("Good morning!    "+name);    }static void Main (string[] args) {chinesegreeting ("Li Lei");    Console.readkey (); }


B. If you want to give a foreigner (do not understand Chinese) greeting, then how to do it? Should know to speak English to foreigners? Create a separate method? Before creating a method, however, we need to use an enumeration type to interpret whether it is a foreigner or a Chinese.

The code is as follows:

public enum language{chinese,english}public void englishgreeting (string name) {Console.WriteLine ("Morning!")    +name); Public Greatpeople (String name,language Language) {switch (Language) {case Language.         English:englishgreeting (name); break; Case language.      Chinese:chinesegreeting (name); break; }  }

As long as some programming experience people know that the above solution is not good, if the next time there are Japanese, Korean, Africans and so on, then we have to add enumeration elements, add greeting Method! The above method is not conducive to expansion. So we're wondering if there's anything we can do that doesn't have to be that much trouble and expand well? I now analyze how the above solution is done.


The first way to add a corresponding language greeting is not limited, the enumeration element is also necessary, the enumeration element is to determine which language to call the greeting method to greet the flag, then since we mentioned before the method can be used to do the parameter then why not directly to the method name? Here is the code to implement the above scenario using the proxy:


 public delegate void greetingdelegate (string name);     class  Program    {        public static  Void englishgreeting (String name)         {             console.writeline ("morning! "+name);        }         Public static void chinesegreeting (String name)          {            console.writeline ("Good morning!") " + name);        }         //this is a         public static void  Greetingpeople (String name, greetingdelegate greetingmethOD)         {                         greetingmethod (name) ;//                     }        static void main (string[]  args)         {             greetingpeople ("Mike",  englishgreeting);             greetingpeople ("Li Lei",  chinesegreeting);             console.readkey ();        }     }

Look at the above code, is not feeling much more comfortable we do not have to use the enumeration, and do not have to choose (switch).

Please note: publicstatic void Greetingpeople (string name, Greetingdelegate Greetingmethod) This method uses a delegate type parameter to pass the greeting method used. It feels amazing.


Do you have some feeling about the commission when you see the demo above? Now my question is coming again.

3. How is the method bound to the delegate?

This problem I also need to borrow the above demo to modify, so as to show the effect. The demo code is as follows:

Public delegate void greetingdelegate (String name);    class  Program    {        public static void  englishgreeting (String name)         {             console.writeline ("Morning," +name);         }        public static void  chinesegreeting (String name)         {             console.writeline ("Good morning!") " + name);        }         public static void greetingpeople (string name, greetingdelegate  Greetingmethod)         { &NBsp;          console.writeline ("Greetings start ...");             greetingmethod (name);             console.writeline ("Greetings end! ");         }        static  void main (String[] args)         {             greetingdelegate delegate1;//example of a delegate              delegate1 = EnglishGreeting;             delegate1 += ChineseGreeting;             greetingpeople ("Mike",  englishgreeting);             greEtingpeople ("Li Lei",  chinesegreeting);             greetingpeople ("John",  delegate1);             console.readkey ();         }    }


The results are as follows:

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M01/4C/D1/wKiom1RFytiy5BwmAAB0Uhk_LI8973.jpg "title=" 1.PNG " alt= "Wkiom1rfytiy5bwmaab0uhk_li8973.jpg"/>


multiple methods can be bound to a delegate instance.


Note: delegate1 = englishgreeting; this operator "=" is the initialization of the delegate instance, then "+ =" is the binding syntax. So in the end


Initialization and binding can also do this:

    

             greetingdelegate delegate1;             delegate1 = englishgreeting;             delegate1 += chinesegreeting;             greetingpeople ("John",  delegate1);             greetingdelegate delegate2 = new greetingdelegate (EnglishGreeting);             delegate2 += ChineseGreeting;             greetingpeople ("LiLy",  delegate2) ;             console.readkey (); 

In this way, the delegate is not very similar to the class! The following code and information you will find more and more like.


Greetingdelegate delegate3 = new Greetingdelegate ();//error, not including 0 parameters of the constructor delegate3 + = englishgreeting; Console.readkey ();

Indicates that the compiler compiles the delegate as a class when compiling. This is also not a function pointer.


Summarize:

Greetingdelegate
1. Delegate definition

The Declaration prototype of a delegate is
Delegate < function return type > < delegate name > (< function parameter >)
Example: public delegate void Greetingdelegate (string name);//defines a delegate that can register a function that returns a void type and has an int as a parameter so that a delegate is defined. But the delegate is equivalent to declaring a class within. NET, and if the class is not instantiated as an object, many functions are not available, and so are the delegates.


2. Delegate instantiation

The prototype of the delegate instantiation is
< delegate type > < instance alias >=new < delegate type > (< registration function >)
Example: Checkdelegate _checkdelegate=new checkdelegate (CHECKMOD);//using a function Checkmod to instantiate the above Checkdelegate delegate as _checkdelegate
At the beginning of. NET 2.0, you can instantiate a delegate directly with a matching function:
< delegate types > < instance aliases >=< registration functions >
Example: Checkdelegate _checkdelegate=checkmod;//using function Checkmod to instantiate the above Checkdelegate delegate as _checkdelegate now we can use the delegate like a function, In the example above, now executing _checkdelegate () is equivalent to executing checkmod (), the most important thing is now the function Checkmod equivalent to put in the variable, it can be passed to other Checkdelegate reference object, It can also be passed as a function parameter to other functions or as a return type of a function


3. Initializing delegates with anonymous functions

Above in order to initialize the delegate to define a function is not feeling a bit of trouble, and the delegate is assigned to the function is usually called by the delegate instance, rarely directly call the function itself.

With this in. NET 2.0, the anonymous function was born, and because the anonymous function had no name, it had to be referenced with a delegate instance, and the anonymous function was defined to initialize the delegate

The anonymous function initializes the prototype of the delegate:

< delegate type > < instance alias >=new < delegate type > (delegate (< function parameter >) {function Body});

Of course, after. NET 2.0, you can use:

< delegate type > < instance alias >=delegate (< function parameter >) {function Body};


DELEGATE&NBSP;VOID&NBSP;FUNC1 (int i);         delegate int &NBSP;FUNC2 (int i);         static func1 t1 =new  func1 (Delegate (int i)         {             console.writeline (i);         });        static func2 t2;         static void main (String[] args)          {            t2 =  Delegate (INT&NBSP;J)             {                 return j;          &NBSP;&NBSP;&NBSP;};&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;T1 (2);                          console.writeline (T2 (1));                     }

Of course, in. NET 3.0 there is something more convenient than the anonymous function lambda expression, which is not said here.


4. Generic delegate
Delegates also support the use of generics
Generic delegate Prototypes:
Delegate <T1> < delegate name ><T1,T2,T3...> (T1 t1,t2 t2,t3 t3 ...)
Example:
Delegate T2 a<t1,t2> (T1 t);//defines a delegate with two generics (T1,T2), T2 as a delegate function return type, T1 as a delegate function parameter type

static int test (int t)
{
return t;
}

static void Main (string[] args)
{
A<int, int> a =test;//the generic delegate delegate <T1,T2> instantiate to <int,int>, that is, a function that has an int type argument and the return type is int, so test is used to instantiate the delegate
Console.WriteLine (A (5));//Output 5
}

5. Delegation of multicast
When you instantiate a delegate, you see that you must register a matching function with a delegate to instantiate a delegate object, but an instantiated delegate can register more than one function, register multiple functions, and then execute each of the registration functions according to the registration sequence of the registered function when the delegate is executed.
Prototype of the function registration delegate:
< delegate type > < instance alias >+=new < delegate type > (< registration function >)
Example: Checkdelegate _checkdelegate=new checkdelegate (CHECKMOD);//Register the function checkmod on the delegate instance _checkdelegate
At the beginning of. NET 2.0, you can register a matching function directly with the instantiation delegate:
< delegate types > < instance aliases >+=< registration functions >
Example: checkdelegate _checkdelegate+=checkmod;//registering a function checkmod on a delegate instance _checkdelegate
After that we can also register multiple functions on the delegate:
Example: _checkdelegate+=checkpositive;//registering a function checkpositive on a delegate instance _checkdelegate
_checkdelegate ();//execution of this delegate instance executes checkmod () before executing checkpositive ()

actually using the + = symbol will determine
If the delegate is not instantiated at this time (the delegate instance is null), it automatically instantiates the delegate with the function on the right of + =
If the delegate is instantiated at this point, it will only register the function on the right of + = on the delegate instance
It is also important to note that if a delegate instance that is registered with a function is assigned from the new = sign, it is equivalent to re-instantiating the delegate, and before the function and the delegate instance are registered above, there is no relationship between them, the following example will talk about this!

Of course there is the + = Registration function to the delegate, also has the-= de-Registration
Example: _checkdelegate-=new checkdelegate (checkpositive);//de-checkpositive the registration of _checkdelegate
_checkdelegate-=checkpositive;//.net 2.0 can be started in this way to unlock the registration

This article is from the "Love Coffee" blog, please be sure to keep this source http://4837471.blog.51cto.com/4827471/1566221

The delegation of C # advanced programming

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.