完整的測試代碼如下:
使用委托的完整測試代碼
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}