This article tries to use C # Language To describe the overview of delegation and events. I hope this article will help you understand the concept of delegation and events, understand the purpose of delegation and events, and understand its C # implementation. Method To understand the benefits of delegation and events. C # Is a new language. I hope you can see it clearly in this article, so that you can have a deeper understanding and exploration of commissioned, event, and other technologies.
1. Delegate
Nature of delegation
-- In C #, delegate is a special class;
-- To some extent, it is equivalent to the function pointer of C ++;
-- To some extent, it is equivalent to an Interface );
Definition of delegation
-- Keyword: delegate
-- Public delegate void MyDelegate (string message );
Note: here we first understand a concept. What is a function signature? (I will not explain it too much here. You can understand this concept ).
Use Delegation
Let's take a look at a small delegation example:
How do we design a simple addition and subtraction method? Take a look at the following code:
1 class Program
2 {
3/** // <summary>
4 // addition operation
5 /// </summary>
6 /// <param name = "x"> x </param>
7 // <param name = "y"> y </param>
8 /// <returns> </returns>
9 private static int Add (int x, int y)
10 {
11 int result = x + y;
12 Console. WriteLine ("x + y = {0}", result );
13 return result;
14}
15
16/** // <summary>
17 // Subtraction
18 /// </summary>
19 /// <param name = "x"> x </param>
20 /// <param name = "y"> y </param>
21 /// <returns> </returns>
22 private static int Sub (int x, int y)
23 {
24 int result = x-y;
25 Console. WriteLine ("x-y = {0}", result );
26 return result;
27}
28
29 static void Main (string [] args)
30 {
31 Add (8, 8 );
32 Sub (8, 1 );
33 Console. Read ();
34}
35}
The above code can be understood and written by anyone who has learned the program. But how can we handle + through delegation? See the following definition:
1 namespace DelegateSample1
2 {
3 // define a delegate
4 public delegate int OperationDelegate (int x, int y );
5 public class Operator
6 {
7 private int _ x, _ y;
8 public Operator (int x, int y)
9 {
10 this. _ x = x;
11 this. _ y = y;
12}
13
14 public void Operate (OperationDelegate del)
15 {
16 del (_ x, _ y );
17}
18}
19}
The preceding definition requires two int parameters to return the int type. Operator provides an operation Method With a delegate parameter. How can I handle this simple operation through delegation? Okay. Now let's modify the master method we previously defined as follows:
1 namespace DelegateSample1
2 {
3 class Program
4 {
5/** // <summary>
6 // addition operation
7 /// </summary>
8 /// <param name = "x"> x </param>
9 // <param name = "y"> y </param>
10 /// <returns> </returns>
11 private static int Add (int x, int y)
12 {
13 int result = x + y;
14 Console. WriteLine ("x + y = {0}", result );
15 return result;
16}
17
18/*** // <summary>
19 // Subtraction
20 /// </summary>
21 /// <param name = "x"> x </param>
22 // <param name = "y"> y </param>
23 // <returns> </returns>
24 private static int Sub (int x, int y)
25 {
26 int result = x-y;
27 Console. WriteLine ("x-y = {0}", result );
28 return result;
29}
30
31 static void Main (string [] args)
32 {
33 // declare a delegate object
34 OperationDelegate del = null;
35 del + = new OperationDelegate (Add );
36 del + = new OperationDelegate (Sub );
37
38 Operator op = new Operator (5, 3 );
39 op. Operate (del );
40 Console. ReadLine ();
41}
42}
43}
44
From the above example, the delegate OperationDelegate represents a group of methods whose signature is:
-- Return Value: int; parameter: int, int;
As long as the method that complies with the signature can be assigned to this delegate: From the above, it is not difficult to see that I want to create a delegate, as defined below:
1 OperationDelegate del + = new OperationDelegate (method name );
We can see from the above that the (+ =) operator also has the (-=) operator? This involves another concept, the delegated chain.
-- Delegated chain: in fact, a delegated instance is a delegated chain, + = indicates adding a delegated instance to the delegated chain, and-= indicates removing the delegated instance.
1 OperationDelegate del = null;
2del + = new OperationDelegate (Add); // Add a delegated instance to the delegated chain
3del-= new OperationDelegate (Add); // remove the delegated instance
One of the meanings of delegation
-- Delegation can improve the degree of reuse of programs;
-- Delegate wants to be an interface to a certain extent;
For example, the method Operate () in the preceding example accepts a delegate type, so we can assign different methods to the delegate type to change the nature of Operate.
Let's take a look at another example:
-- We want to output a string of numbers from 0 to 100;
-- Three output requirements are required;
-1. output to the console
-2. output to The ListBox in the form;
-3. output to a text file;
Solution:
-- Use the delegate and interface. The Code is as follows:
1 namespace DelegateSample2
2 {
3 // define a delegate
4 public delegate void ShowNumberDel (object [] items );
5 public class ProcessNumber
6 {
7 private object [] items;
8 public ProcessNumber (int max)
9 {
10 items = new object [max];
11 for (int I = 0; I <max; ++ I)
12 {
13 items [I] = I;
14}
15}
16
17 public void ProcessItems (ShowNumberDel show)
18 {
19 show (items );
20}
21}
22}
23
Here, we first deploy the controls on the interface and prepare for calling the delegate. The effect and Code are as follows:
The Code is as follows:
1 private ProcessNumber pn = null;
2 ShowNumberDel del = null;
3
4 private void Form1_Load (object sender, EventArgs e)
5 {
6 pn = new ProcessNumber (100 );
7}
8
9 // go to the console
10 private void ShowInConsole (object [] items)
11 {
12 foreach (object item in items)
13 {
14 Console. WriteLine (item );
15}
16}
17
18 // to ListBox
19 private void ShowInListBox (object [] items)
20 {
21 listBox1.Items. Clear ();
22 foreach (object item in items)
23 {
24 listBox1.Items. Add (item );
25}
26}
27
28 // to a text file
29 private void ShowInFile (object [] items)
30 {
31 using (StreamWriter sw = new StreamWriter ("Test.txt", true ))
32 {
33 foreach (object item in items)
34 {
35 sw. WriteLine (item );
36}
37}
38}
Delegated use:
1private void button1_Click(object sender, EventArgs e)
2{
3 pn.ProcessItems(new ShowNumberDel(ShowInConsole));
4}
5
6private void button2_Click(object sender, EventArgs e)
7{
8 pn.ProcessItems(new ShowNumberDel(ShowInListBox));
9}
10
11private void button3_Click(object sender, EventArgs e)
12{
13 pn.ProcessItems(new ShowNumberDel(ShowInFile));
14}
15
16private void button4_Click(object sender, EventArgs e)
17{
18 del += new ShowNumberDel(this.ShowInListBox);
19 del += new ShowNumberDel(this.ShowInFile);
20
21 pn.ProcessItems(del);
22}
The complete test code is as follows:
Use the complete test code of the Delegate
1using System;
2using System.Collections.Generic;
3using System.ComponentModel;
4using System.Data;
5using System.Drawing;
6using System.Text;
7using System.Windows.Forms;
8using System.IO;
9
10namespace DelegateSample2
11{
12 public partial class Form1 : Form
13 {
14 public Form1()
15 {
16 InitializeComponent();
17 }
18
19 private ProcessNumber pn = null;
20 ShowNumberDel del = null;
21
22 private void Form1_Load(object sender, EventArgs e)
23 {
24 pn = new ProcessNumber(100);
25 }
26
27 private void ShowInConsole(object[] items)
28 {
29 foreach (object item in items)
30 {
31 Console.WriteLine(item);
32 }
33 }
34 private void ShowInListBox(object[] items)
35 {
36 listBox1.Items.Clear();
37 foreach (object item in items)
38 {
39 listBox1.Items.Add(item);
40 }
41 }
42 private void ShowInFile(object[] items)
43 {
44 using (StreamWriter sw = new StreamWriter("Test.txt", true))
45 {
46 foreach (object item in items)
47 {
48 sw.WriteLine(item);
49 }
50 }
51 }
52
53 private void button1_Click(object sender, EventArgs e)
54 {
55 pn.ProcessItems(new ShowNumberDel(ShowInConsole));
56 }
57
58 private void button2_Click(object sender, EventArgs e)
59 {
60 pn.ProcessItems(new ShowNumberDel(ShowInListBox));
61 }
62
63 private void button3_Click(object sender, EventArgs e)
64 {
65 pn.ProcessItems(new ShowNumberDel(ShowInFile));
66 }
67
68 private void button4_Click(object sender, EventArgs e)
69 {
70 del += new ShowNumberDel(this.ShowInListBox);
71 del += new ShowNumberDel(this.ShowInFile);
72 pn.ProcessItems(del);
73 }
74 }
75}
Meaning 2 of delegation
-- Delegate is required to use threads in C #.
-Thread thread = new Thread (new ThreadStart (target ));
-ThreadStart is a delegate. Its definition is:
-Target indicates the method name of the ThreadStart delegate;
-- Function callback
-When we define a delegate;
public delegate void MyDelegate(int source);
-For Asynchronous calls, there are BeginInvoke () and EndInvoke () methods;
-Del. BeginInvoke (source, new System. AsyncCallback (CallBack), "test ");
-private void CallBack(IAsyncResult asyncResult)
{
int result = del.EndInvoke(asyncResult);
//......
}
What is function callback? This topic is for discussion and will not be elaborated here. This article is only an entry-level article about delegation. For more details about delegation, please refer to the specific books or materials. This article will briefly introduce it here.