C # delegation, events, and callback Functions

Source: Internet
Author: User

1. Delegate (in some books, it is also called deleGATE)
What is delegation? The meaning of this name has given us the space we imagined. You are programming, and you are writing an ASP. NET web page, and JS is not familiar to you, so you entrust a colleague to help you complete the JS part. This is the delegate that gives what you cannot do to others. But how do I know who is going to do it? Of course, you need to know the name! To distinguish people with the same name, a feature must be described.
In C #, the role of delegation is described as follows: Delegation is like a function pointer, which can be used to call different functions when the program is running. This is actually the same as entrusting your colleagues to complete the JS Code. If two colleagues can do this, they only need to make the results meet your needs (just like an interface), even though they do different processes and make different effects, however, you can meet your requirements.
1. Simple Delegation
What information does the delegate need to carry? First, it stores the method name, the parameter list (method signature), and the returned type. For example:
Delegate string/* return type */ProcessDelegate (int I );
This is the definition of a delegate. The blue part is the keyword for declaring the delegate, the red part is the returned type, and the black part is the delegate type name, which is similar to a class name, while the () part is the parameter part. It means that if you want to use this delegate to do things, the method of doing things must meet the following conditions:
1. The return type is the same as the return type of the Delegate. Here the return type is string;
2. It can have only one parameter and is of the int type.
OK. If the above two conditions are met, everything can work :)
For example:

1 using System;
2 using System. Collections. Generic;
3 using System. Text;
4
5 namespace TestApp
6 {
7 /// <summary>
8 // delegate
9 /// </summary>
10 /// <param name = "s1"> </param>
11 /// <param name = "s2"> </param>
12 /// <returns> </returns>
13 public delegate string ProcessDelegate (string s1, string s2 );
14
15 class Program
16 {
17 static void Main (string [] args)
18 {
19/* Call Method */
20 ProcessDelegate pd = new ProcessDelegate (new Test (). Process );
21 Console. WriteLine (pd ("Text1", "Text2 "));
22}
23}
24
25 public class Test
26 {
27 /// <summary>
28 // Method
29 /// </summary>
30 /// <param name = "s1"> </param>
31 /// <param name = "s2"> </param>
32 /// <returns> </returns>
33 public string Process (string s1, string s2)
34 {
35 return s1 + s2;
36}
37}
38}

The output result is:
Text1Tex2
2. Generic Delegation
Generic delegation means that the type of the parameter is unknown. For example, the Code is rewritten:

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", 100 ));
}
}
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 output result is:
Text1100
The details of generics are beyond the scope of this article.
Ii. Events

When an event occurs, one object can notify another object through the event. For example, when the front-end interface is completed, he notifies you that the front-end can be integrated with the program you developed. This is an event. It can be seen that an event triggers another thing at a time node, but he does not care how to do it. In terms of events, the key point is when and who will do it.
In C #, the time definition keyword is event. For example:
Event ProcessDelegate ProcessEvent;
The entire event definition method and 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 (object sender, EventArgs e );
Class Program
{
Static void Main (string [] args)
{
/* Step 1 */
Test t = new Test ();
/* Associated event method, which is equivalent to finding the principal */
T. ProcessEvent + = new ProcessDelegate (t_ProcessEvent );
/* Enter the Process method */
Console. WriteLine (t. Process ());
Console. Read ();
}
Static void t_ProcessEvent (object sender, EventArgs e)
{
Test t = (Test) sender;
T. Text1 = "Hello ";
T. Text2 = "World ";
}
}
Public class Test
{
Private string s1;
Public string Text1
{
Get {return s1 ;}
Set {s1 = value ;}
}
Private string s2;
Public string Text2
{
Get {return s2 ;}
Set {s2 = value ;}
}
Public event ProcessDelegate ProcessEvent;
Void ProcessAction (object sender, EventArgs e)
{
If (ProcessEvent = null)
ProcessEvent + = new ProcessDelegate (t_ProcessEvent );
ProcessEvent (sender, e );
}
// If no associated method is specified, an error will be thrown when this method is called.
Void t_ProcessEvent (object sender, EventArgs e)
{
Throw new Exception ("The method or operation is not implemented .");
}
Void OnProcess ()
{
ProcessAction (this, EventArgs. Empty );
}
Public string Process ()
{
OnProcess ();
Return s1 + s2;
}
}
}

What does it feel? Is it similar to code injection, so you can use any code that conforms to the delegate interface (the delegate is really like the interface) to inject it into the Process. Assign a value to him before he returns the result.
Iii. Callback Functions
Tired of typing so many words!
The callback function transmits a method to another method for execution. C # has many callback functions, such as asynchronous operations. Here is 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 (string 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 process (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 result:
Text1Text2
Text1
Text2
Text2Text1
The Process method calls a callback function. Of course, only the callback function is executed here. It can be seen that any method conforming to this delegate can be passed in, meaning that this part of code is variable. In terms of design, there is a principle to extract the variable part of the code, which can undoubtedly be used in that scenario.
Http://birdshover.cnblogs.com Birdshover

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.