Detailed explanation of the delegate, event and callback function in C # _c# tutorial

Source: Internet
Author: User

. NET programming is the most frequently used element, the event must be one of them. Whether in asp.net or winfrom development, form load (load), Draw (Paint), Initialize (init), and so on.

The code "protected void Page_Load (object sender, EventArgs e)" is believed to be unfamiliar to anyone. Be careful, you will find that very many event methods are with "object sender, EventArgs e" These two parameters. Is this very similar to a delegate?

One, commissioned (in some books also known as delegation)

What is a commission? The meaning of this name has given us the imagination of space, you are programmed, you are now writing a asp.net web page, and JS is unfamiliar to you, so you commissioned a colleague to help you complete the JS section. This is the entrustment to give to others what you cannot do. And how do you know which one is going to do it? Of course you know the name! and in order to distinguish the names of different people, therefore, a feature needs to be described.

In C #, the role of a delegate is described in this way: a delegate is like a pointer to a function that can be used to invoke a different function when the program is run. This is actually the same as you entrust your colleagues to complete the JS code. If you have two colleagues who can do this, they can just do what you want (like an interface), and even though they do it differently and have a different effect, it's OK to meet your requirements.

1, a simple delegation

What information does the delegate need to carry? First, it stores the method name, the parameter list (method signature), and the type returned. Like what:

Delegate string/* return type */processdelegate (int i);

This is the definition of a delegate. The blue part is the keyword that declares the delegate, the red part is the returned type, and the black part is the type name of the delegate, similar to a class name, and () is the parameter part. It means that you have to use this delegate to do things, then the way to do things must meet the following conditions:

1. The return type is consistent with the return type of the delegate, here is the string type;

2, can and only have one parameter, and is an int type.

OK, meet the above two conditions, everything can work:

For example:

Using System;
 Using System.Collections.Generic;
 Using System.Text; 
 Namespace TestApp
 {
   ///<summary>
  ///delegate
   ///</summary>
   ///<param name= "S1" > </param>
   ///<param name= "s2" ></param>
   ///<returns></returns>
   Public Delegate string Processdelegate (string s1, string s2);
 
   Class program
   {
     static void Main (string[] args)
     {/
       * Call method */
       processdelegate PD = new Processdelegate (New Test (). Process);
       Console.WriteLine (PD ("Text1", "Text2"));
     }
 
   public class Test
   {
     ///<summary>
     ///method
     ///</summary>
     ///<param name= "S1" ></param>
     ///<param name= "s2" ></param>
     ///<returns></returns>
     public string Process (string s1,string s2)
     {return
       s1 + s2;
     }
   }
 }

The result of the output is:

Text1tex2

2. Generic delegate

A delegate of a generic type, that is, the type of the parameter is indeterminate, for example, if the code is rewritten as:

Using System;
Using System.Collections.Generic;
Using System.Text;

Namespace TestApp
{
  ///<summary>
  ///delegate
  ///</summary>
  ///<param name= "S1" > </param>
  ///<param name= "s2" ></param>
  ///<returns></returns>
  Public Delegate string processdelegate<t,s> (T s1, S S2);

  Class program
  {
    static void Main (string[] args)
    {/
      * Call method
      /* Processdelegate<string,int > PD = new processdelegate<string,int> (new Test (). Process);
      Console.WriteLine (PD ("Text1");
    }

  public class Test
  {
    ///<summary>
    ///method
    ///</summary>
    ///<param name= "S1" ></param>
    ///<param name= "s2" ></param>
    ///<returns></returns>
    public string Process (string s1,int s2)
    {return
      s1 + s2;
    }
  }
}

The result of the output is:

Text1100

The details of generics are outside the scope of this article and are not added here.

II. Events

When something happens, an object can notify another object through an event. For example, the front desk completes the front interface, and he informs you that you can integrate the foreground and the program you developed. This is an event. You can see that the event is a time node to trigger another thing, and the other thing how to do, he does not care. In terms of events, the key point is when and who to do it.

In C #, the time definition keyword is event. For example:

Event Processdelegate processevent;

The entire event definition method and the execution process:

Using System;
Using System.Collections.Generic;

Using System.Text; namespace TestApp {///<summary>///delegate///</summary>///<param name= "S1" ></param>// /<param name= "s2" ></param>///<returns></returns> public delegate void Processdelegate (objec

  T sender, EventArgs e);
      Class Program {static void Main (string[] args) {/* First step */Test t = new Test ();
      /* Associated event method, equivalent to find the client/t.processevent + = new Processdelegate (t_processevent); 

      /* Enter the Process method * * Console.WriteLine (t.process ());
    Console.read ();
      The static void T_processevent (object sender, EventArgs e) {Test t = (test) sender;
      T.text1 = "Hello";
    T.TEXT2 = "World";

    The public class Test {private string S1;
      public string Text1 {get {return s1;}
    set {S1 = value;}

    private string S2; public string Text2 {get {s2;
    set {s2 = value;}

    public event Processdelegate processevent; void Processaction (object sender, EventArgs e) {if (processevent = = null) processevent + = new PROCESSDE
      Legate (t_processevent);
    processevent (sender, E);  //If you do not specify the association method yourself, the method will be called to throw the error void t_processevent (object sender, EventArgs e) {throw new Exception ("the

    method or operation are not implemented. ");
    void Onprocess () {processaction (this, eventargs.empty);
      public string Process () {onprocess ();
    return s1 + s2;

 }
  }
}

What did you feel? is the same as code injected into the process, which is equivalent to any code that conforms to the delegate interface (the delegate does look like an interface). Assign a value to him before he returns.

Third, callback function

Hit so many words, very tired ah!

The callback function is to pass a method to another method to execute. There are many callback functions in C #, such as asynchronous operations. Here's an example:

Using System;
Using System.Collections.Generic;

Using System.Text; namespace TestApp {///<summary>///delegate///</summary>///<param name= "S1" ></param>// /<param name= "s2" ></param>///<returns></returns> Public delegate string Processdelegate (str

  ing s1, string s2);
      Class Program {static void Main (string[] args) {/* Call method */Test t = new Test ();
      string r1 = t.process ("Text1", "Text2", New Processdelegate (T.PROCESS1));
      string r2 = t.process ("Text1", "Text2", New Processdelegate (T.PROCESS2));

      String r3 = t.process ("Text1", "Text2", New Processdelegate (T.PROCESS3));
      Console.WriteLine (R1);
      Console.WriteLine (R2);
    Console.WriteLine (R3); public class Test {public string process (string s1,string s2,processdelegate process) {return P
    Rocess (s1, S2);
    public string Process1 (string s1, string s2) {return s1 + s2;
}
    public string Process2 (string s1, string s2) {return S1 + Environment.NewLine + s2;
    public string Process3 (string s1, string s2) {return s2 + S1;

 }
  }
}

Output results:

Text1text2
Text1
Text2
Text2text1

The process method called a callback function, and of course only the callback function was executed here. As you can see, you can pass in any method that conforms to this delegate, meaning that this part of the code is variable. The design has a rule that pulls out the variable parts of the code, and this usage can undoubtedly be used for that occasion.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.