[. NET Basics]-delegate, event, thread (1),. net delegate

Source: Internet
Author: User

[. NET Basics]-delegate, event, thread (1),. net delegate
1. Delegation is the list of pointers for storing methods, that is, the container for loading methods.

A. Create A winform project [01 Delegate]. Add the dg_SayHi.cs delegate class to the Project for storage methods.

Namespace _ 01 delegate {// define delegate [Class] delegate void dg_SayHi ();}

B. In Winfrom, add the button "delegate", click the button event "btnDelegate_Click" to create a delegate object, and add or remove the delegate object:

/// <Summary> /// click the button event /// </summary> private void btnDelegate_Click (object sender, EventArgs e) {// The delegate is the container of the method, you can add or remove methods in the delegate object // create the delegate object, and add the SayHiCN method dg_SayHi objSayHi = new dg_SayHi (SayHiCN) through the constructor ); // Add "One method objSayHi + = SayHiEN to the delegate object; // remove" One method objSayHi-= SayHiCN from the delegate object; // call the delegate, A delegate is a method container. When a delegate is called, all the methods in the delegate are called objSayHi ();} void SayHiCN () {MessageBox. show ("Hello shanghai");} void SayHiEN () {MessageBox. show ("hi shanghai ");}}

C. Click "delegate" to view the effect:

    

D. An image to explain the above running process:

   

2. The return type of the delegate is the same as the return type of the method added to the delegate.

The delegate can be used as a parameter to pass the method. The delegate object is used as a parameter, and the delegate object is the container of the method (in the ellipse). In this way, the method is actually passed. In the above example, We just added the method to the delegate, the delegate has not been passed as a parameter. Let's look at the followingExample

A. We have two methods to obtain the maximum number of int arrays.Int GetMaxNum ()And obtain the decimal number in the int array.Int GetMinNum () 

/// <Summary> // 2.1 returns the maximum number of returned arrays /// </summary> /// <returns> </returns> int GetMaxNum (int [] arr) {int numMax = arr [0]; for (int I = 1; I <arr. length; I ++) {if (arr [I]> numMax) {numMax = arr [I] ;}} return numMax ;} /// <summary> /// 2.2 returns the minimum number in the array /// </summary> /// <returns> </returns> int GetMinNum (int [] arr) {int numMin = arr [0]; for (int I = 1; I <arr. length; I ++) {if (arr [I] <numMin) {numMin = arr [I] ;}} return numMin ;}View Code

B. If we add these two methods to the delegate class, we need to addInt typeInt dg_GetMaxAndMin ()

// Define the delegate [Class] delegate void dg_SayHi (); // define another delegate class, and receive the return method delegate int dg_GetMaxAndMin (int [] arr );

C. Add a button event to read the return values of methods in the delegate.

Private void BtnDelegateAsPara_Click (object sender, EventArgs e) {int [] arr = {1, 2, 5, 6, 7, 12}; // create a delegate object, add the GetMaxNum method dg_GetMaxAndMin objGetMax = new dg_GetMaxAndMin (GetMaxNum) through the constructor; int numMax = objGetMax (arr ); // pass the parameter array // Add the GetMinNum Method to the delegate object objGetMax ++ = GetMinNum; int numMin = GetMinNum (arr); // pass the parameter array MessageBox. show ("Max" + numMax. toString () + "minimum" + numMin. toString ());}

D. click the button to view the effect:

    

AA, we also have a way to return the Person with the largest age

Using System; using System. collections. generic; using System. linq; using System. text; namespace _ 01 delegate {public class Person {# region name string Name; public string name {get {return name ;}set {name = value ;}} # endregion # region age int Age; public int age {get {return age;} set {age = value ;}# endregion }}View Code // <summary> // 2.3 returns the Person with the largest age. // </summary> /// <returns> </returns> Person GetMaxAgePer (Person [] perArr) {Person MaxAgePer = perArr [0]; for (int I = 1; I <perArr. length; I ++) {if (perArr [I]. age> MaxAgePer. age) {MaxAgePer = perArr [I] ;}} return MaxAgePer ;}View Code

BB. If we add the Person class to the delegate, we also need to add the Person class Person dg_GetMax ().

// Define the delegate [Class] public delegate void dg_SayHi (); // define another delegate class, and receive the return method delegate int dg_GetMaxAndMin (int [] arr ); // define another delegate class. The method for receiving the response type "Person" is delegate Person dg_GetMaxAgePer (Person [] perArr );

CC, update button event, create a delegate object of the Person type, and add the Person GetMaxAgePer () method

Private void BtnDelegateAsPara_Click (object sender, EventArgs e) {int [] arr = {1, 2, 5, 6, 7, 12 }; person [] perArr = {new Person {Name = "sweet", Age = 2}, new Person {Name = "Ole", Age = 3 }, new Person {Name = "hmm", Age = 1 }}; // create a delegate object and add the GetMaxNum method dg_GetMaxAndMin objGetMax = new dg_GetMaxAndMin (GetMaxNum) through the constructor ); int numMax = objGetMax (arr); // pass the parameter array // Add the GetMinNum Method to the delegate object objGetMax ++ = GetMinNum; int numMin = GetMinNum (arr ); // pass the parameter array dg_GetMaxAgePer objGetMaxAge = new dg_GetMaxAgePer (GetMaxAgePer); Person per = objGetMaxAge (perArr); MessageBox. show ("Max" + numMax. toString () + "minimum" + numMin. toString (); MessageBox. show (string. format ("maximum age: {0}, age: {1}", per. name, per. age ));}

DD, run to view the running result:

      

3. Rewrite the delegate to a generic delegate and pass it as a parameter.

According to the above example, each of our different return type methods defines the same type of delegation as the return type, which is a little troublesome. Now we useGeneric definition.

A. because we do not know the object to be compared, we first try to write A generic comparison method, as shown below, the comparison object is passed in the method.T [] arrBut we are not sure about the object.Int []Array orPerson []Array.In the for LoopWe also need to add a specific comparison method. This method needs to pass the comparison method through delegation!

Public T GetMax <T> (T [] arr) {T max = arr [0]; for (int I = 0; I <arr. length; I ++) {// compare the size. How can this problem be determined? The object to be determined cannot be determined. It may be of the int type or the Person class} return max ;}

B. The above For loop should pass the two comparison methods below

# Region 2.4 comparison method of two different objects // Comparison of Two integer values int Compare (int a, int B) {int num = 0; if (a> B) {num = 1;} else if (a = B) {num = 0;} else if (a <B) {num =-1;} return num ;} // Compare two Person types: int Compare (Person AA, Person BB) {int num = 0; if (AA. age> BB. age) {num = 1;} else if (AA. age = BB. age) {num = 0;} else if (AA. age <BB. age) {num =-1;} return num ;}# endregionView Code

C. Now we define the delegate that can receive the comparison methods of the above two different objects:Int dg_GetMax <T> (T t1, T t2) 

// Define the delegate [Class] delegate void dg_SayHi (); // define another delegate class, and receive the return method delegate int dg_GetMaxAndMin (int [] arr ); // define another delegate class and receive the delegate Person dg_GetMaxAgePer (Person [] perArr) method with the return type as Person; // define the generic delegate, the delegate receives the Compare method that compares different object sizes. The delegate method has two parameters: t1 and t2. After comparing the two values, the int value public delegate int dg_GetMax <T> (T t1, T t2 );

D. In this way, we can add the delegate parameters in step A to achieve comparison.

/// <Summary> /// 2.3 generic method, obtain the largest element in the array /// </summary> /// <typeparam name = "T"> generic parameter. If int is compared, int is returned, if the comparison is person, return person </typeparam> // <param name = "arr"> Generic Array </param> /// <param name = "dgGetMax"> delegate parameters, passed to install the comparison method DeleGate </param> // <returns> </returns> public T GetMax <T> (T [] arr, dg_GetMax <T> dg) {T max = arr [0]; for (int I = 0; I <arr. length; I ++) {// compare the size. How can this problem be determined? The object to be determined cannot be determined. It may be of the int or Person type. Therefore, the second generic delegate variable is added to the method, the methods in the delegate implement a specific comparison and return values. If 1 is returned, the first number is greater than the second number. if (dg (arr [I], max) = 1) {max = arr [I] ;}} return max; // This max may be int or max}

E. Update button events using the generic delegate we just wrote:

Private void BtnDelegateAsPara_Click (object sender, EventArgs e) {int [] arr = {1, 2, 5, 6, 7, 12 }; person [] perArr = {new Person {Name = "sweet", Age = 2}, new Person {Name = "Ole", Age = 3 }, new Person {Name = "hmm", Age = 1 }}; // We use the written delegate method to Compare the size of dg_GetMax again <int> dg_GetMaxInt = new dg_GetMax <int> (Compare); int numMax = GetMax (arr, dg_GetMaxInt ); dg_GetMax <Person> dg_GetMaxPer = new dg_GetMax <Person> (Compare); Person per = GetMax (perArr, dg_GetMaxPer); MessageBox. show ("Max" + numMax. toString (); MessageBox. show (string. format ("maximum age: {0}, age: {1} years", per. name, per. age); // create the delegate object and add the GetMaxNum method using the constructor // dg_GetMaxAndMin objGetMax = new dg_GetMaxAndMin (GetMaxNum); // int numMax = objGetMax (arr ); // pass the parameter array /// Add the GetMinNum Method to the delegate object // objGetMax + = GetMinNum; // int numMin = GetMinNum (arr); // pass the parameter array // MessageBox. show ("Max" + numMax. toString () + "minimum" + numMin. toString (); // MessageBox. show (string. format ("maximum age: {0}, age: {1}", per. name, per. age ));}View Code

F. Run the command to view the effect:

  

-------- [Download Demo ]-----------

4. Anonymous Method Introduction:

When using Delegate, it is often not necessary to define a common method separately (the Compare method in the above example), because this method is only used by Delegate and only used once, in this case, the anonymous method is suitable.

// 3. Rewrite the Compare method to the delegate method. You can rewrite the Compare method to the anonymous method. // int numMax = GetMax <int> (arr, Compare ); int numMax = GetMax <int> (arr, delegate (int a, int B) {int num = 0; if (a> B) {num = 1 ;} else if (a = B) {num = 0;} else if (a <B) {num =-1 ;}return num ;}); // Person per = GetMax <Person> (perArr, Compare); Person per = GetMax <Person> (perArr, delegate (Person AA, Person BB) {int num = 0; if (AA. age> BB. age) {num = 1;} else if (AA. age = BB. age) {num = 0;} else if (AA. age <BB. age) {num =-1;} return num ;});
5. Delegate is a Class after compilation. This Class inherits from MulticastClass (Multicast delegation)

  We use. NET Relfector to decompile and view the essence of the delegate:

---------------------

A. The essence of delegation is class, inherited from multicast delegation MulticastDelegate, and MulticastDelegate inherited from System. Delegate.

 

B, objSayHi + = SayHiEN; the essence of this Code is: store the methods in both sets in one collection, and then return

/// Create the delegate object and add the SayHiCN method dg_SayHi objSayHi = new dg_SayHi (SayHiCN) through the constructor; // Add "One method objSayHi + = SayHiEN to the delegate object;

The above method is added to the delegate. After compilation, it is as follows:

  

Summary:This article describes delegation, uses delegation as a method for transmission, and comes into contact with generic and anonymous methods. It uses the anti-compiler to view the essence of delegation.

 

Refer:

Returns the value of the method in the delegate: http://m.blog.csdn.net/blog/lrz8745/7325056

Http://www.cnblogs.com/linlf03/archive/2011/05/09/2041657.html

Utility:The Indent Guides plug-in code displays a virtual vertical line.

     

 

 

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.