程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> C#編程利器之四:委托與事件(Delegate and event) (上)(6)

C#編程利器之四:委托與事件(Delegate and event) (上)(6)

編輯:關於C語言

完整的測試代碼如下:

使用委托的完整測試代碼

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}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved