[Aaronyang] C # People love to learn not to learn [7]

Source: Internet
Author: User

making a decision is not difficult, it's hard to put it into action, and stick to the--aaronyang blog (www.ayjs.net)-www.8mi.me
1. Delegation-My summary

1.1 Commission: Interview I will say, the method as a parameter. A delegate contains only the address of one or more methods.

Example 1: (Execute multiple methods of the same method signature at one time)

/** January 3, 2015 23:12:13 Aaronyang * Website: www.ayjs.net www.8mi.me*/usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespacedemo0103{Delegate voidTotalmethod (intType);//The first step delegate method signature defines the appearance of a method, as if an interface    classProgram {Static voidMain (string[] args) {            //Totalmethod TM =new Totalmethod (METHOD1);//or very recommended directly + = or =Totalmethod TM =Method1; TM+=Method2; TM+=Method3; TM (2);//Execute 3 methods at a time
TM. Invoke (3); Or use the Invoke method
Console.ReadLine (); } Static voidMETHOD1 (intt) {Console.WriteLine ("Method1:"+t*Ten+"\ t"); } Static voidMETHOD2 (intt) {Console.WriteLine ("METHOD2:"+ T * -+"\ t"); } Static voidMETHOD3 (intt) {Console.WriteLine ("Method3:"+ T * ++"\ t"); } }}

Effect:

Example 2: An array of delegate types. Take the delegate as a parameter, this technique must master, can write very wonderful code, very much like the JavaScript method. Method of lambda expression first meet

/** January 3, 2015 23:12:13 Aaronyang * Website: www.ayjs.net www.8mi.me*/usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespacedemo0103{Delegate voidTotalmethod (ref intType);//The first step delegate method signature defines the appearance of a method, as if an interface    /// <summary>    ///Process The Totalmethod method, multiplying the converted number by the number of counts by the same number///I did not define a method that is consistent with the signature of this delegate method, using a lambda expression to define a method/// </summary>    /// <param name= "Total" ></param>    /// <param name= "Count" ></param>    /// <returns></returns>    Delegate intProcesstotalmethod (Totalmethod Total,intcount); classProgram {Static voidMain (string[] args) {            //Totalmethod TM =new Totalmethod (METHOD1);//or very recommended directly + = or =//Totalmethod TM = METHOD1; //TM + = METHOD2; //TM + = Method3; //TM (2);//Execute 3 methods at a time//TM. Invoke (3);//or use the Invoke methodtotalmethod[] TMS= {Method1, Method2, Method3};//Delegate Array            intinittypenum=2; Processtotalmethod PTM= (x, y) = ={x (refInittypenum);//multiplies the init by 10,100,1000 times and returnsConsole.WriteLine ("multiply numbers by multiples:"+inittypenum); //then multiply the Y-inittypenum in a row .                 for(inti =0; i < Y; i++) {Inittypenum*=Inittypenum; }                returnInittypenum;            }; Console.WriteLine ("Finally, the number after multiplying 2 times consecutively:"+ PTM (tms[0],2));        Console.ReadLine (); }        Static voidMETHOD1 (ref intt) {T= T *Ten; Console.WriteLine ("Method1:"+t+"\ t"); }        Static voidMETHOD2 (ref intt) {T= T * -; Console.WriteLine ("METHOD2:"+ T +"\ t"); }        Static voidMETHOD3 (ref intt) {T= T * +; Console.WriteLine ("Method3:"+ T +"\ t"); }    }}

Effect:

1.2 The frame comes with the good common action<t1,[t2] ... [t8]> and Func<t1,t2. [t8]> can see the Func tutorial I wrote: view

The Action is a void delegate, where T1,t2: T8 are parameters of a method, and Func is a, the last generic parameter is the return value, preceded by the parameter of the method, for example func<int,string,double> then the last double is the return value type, preceded by the parameter of the method signature, which is equivalent to defining the

Delegate double Method1 (int,string);

About Func can write a lot of wonderful code, really look forward to everyone's play.

1.3 Multicast delegation

A simple example of a multicast delegate is explained in 1.1 Example 1.

Aaronyang: One delegate binds multiple methods and then executes the delegate, if the delegate defines a method signature that is void, then executes sequentially, and if an error occurs, the iteration stops. If a delegate-defined method signature has a return value, such as a type such as int,string, only the last result is visible. Delegates can use + = To increase method invocation, using the

-= Delete method call.

Next, the Getinvocationlist () method that demonstrates a delegate class returns an delegate array

1.4 Anonymous methods in fact, in 1.3 we have already seen, direct (method parameter) =>{method body} to easily define a method type. If there is only one method argument, the parentheses can be removed, such as the X=>{method body}

It can also be a little annoying to add a delegate keyword, such as func<string,string> a=delegate (string s) {return s} is also equivalent to func<string,string& Gt A = S=>{return s} is also equivalent to func<string,string> a = s = = "modified:" +S;

1.5 closures: Lambda expressions can access variables outside the lambda expression; possible problem: if the multithreaded environment modifies the value of the Lambdawai variable, the result may be incorrect.

            int5;            Func<int,int> f = x = x+Lambdawai;             //    output 5;            Console.WriteLine (f (3//    output 8;

*1.6 C # 5.0 Very big change, the closure reference of the foreach statement article: article

Personal small try: Win8.1 didn't find. Problem

Case: The following code outputs what, c#4.0 output 5,5,5,5,5 c#5.0 output 1,2,3,4,5

            int[] data =New int[] {1,2,3,4,5 }; List<Func<int>> actions =Newlist<func<int>>(); foreach(intXinchdata) {actions. Add (()=x); }            foreach(varFooinchactions)            {Console.WriteLine (foo ()); }

C # 4.0 foreach execution principle: True output 5 x 5

   int[] data =New int[] {1,2,3,4,5 }; List<Func<int>> actions =Newlist<func<int>>(); IEnumerator e=data.            GetEnumerator (); intx =0;  while(E.movenext ()) {x= (int) e.current; Actions. Add (()=x); }            foreach(varFooinchactions)            {Console.WriteLine (foo ()); }

Note that the iteration variable x is defined outside the loop block.
Here is a very important concept, closures, in lambda expressions, we use the outer free variable x, note that when the lambda expression is called, X is evaluated, and this definition of the external x variable at the end of the loop equals 5, which is why the output 5 is why

C # 5.0 foreach execution principle: Yes 1,2,3,4,5

int[] data =New int[] {1,2,3,4,5 }; List<Func<int>> actions =Newlist<func<int>>(); IEnumerator e=data.            GetEnumerator ();  while(E.movenext ()) {intx =0; X= (int) e.current; Actions. Add (()=x); }            foreach(varFooinchactions)            {Console.WriteLine (foo ()); }

This time, we define x to the inside of the block. So every time the loop executes, a local variable x is generated, and the closure is evaluated individually for each iteration, so the output is the 12345 we expect.

If you want to get 1,2,3,4,5, you can modify the code:

            int[] data =New int[] {1,2,3,4,5 }; List<Func<int>> actions =Newlist<func<int>>(); foreach(intXinchdata) {                intX1 =x; Actions. Add (()=x1); }            foreach(varFooinchactions)            {Console.WriteLine (foo ()); }

1.7 Event-A special delegate, such as the Click event of a WinForm button

Custom events, calls to generic events, event listeners, weak events, generic weak events, expression usages, and much more, will be discussed separately in the next chapter.

====== Anhui Liuan =========www.ayjs.net==========aaronyang======== Yang Yang ========www.8mi.me==========

[Aaronyang] C # People love to learn not to learn [7]

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.