class
1using System;
2using System.Collections.Generic;
3using System.Runtime.InteropServices;
4using System.Text;
5
6namespace ConsoleApplication6
7{
8 class Program
9 {
10 static void Main(string[] args)
11 {
12 Demo obj = new Demo();
13 obj.myEvent+=new Demo.myDelegate(obj_myEvent);
14 obj.Run();
15 Console.ReadLine();
16 }
17
18 private static void obj_myEvent(object sender, EventArgs e)
19 {
20 Console.Write("目前時間:" + DateTime.Now.ToLocalTime());
21 }
22 }
23
24 //事件處理常式委託的標準簽名定義一個沒有傳回值的方法,其第一個參數的類型為 Object,它引用引發事件的執行個體,
25 //第二個參數從 EventArgs 類型派生,它儲存事件數目據。如果事件不建置事件資料,則第二個參數只是 EventArgs 的一個執行個體。否則,第二個參數為從 EventArgs 派生的自訂類型,
26 //提供儲存事件數目據所需的全部欄位或屬性。
27
28 class Demo
29 {
30 public delegate void myDelegate(object sender, EventArgs e);//定義委託
31 public event myDelegate myEvent;//定義委託類型的事件
32 //定義委託類型的方法
33 public void Run()
34 {
35 //定義一個每一秒鐘觸發的計時器
36 System.Timers.Timer myTimer = new System.Timers.Timer(1000);
37 //定義時間間隔所要處理的方法, EventHandler 是一個預定義的委託,專用於表示不產生資料的事件的事件處理常式方法。如果事件產生資料,則必須提供自己的自訂事件數目據類型,
38 //並且必須要麼建立一個委託,其中第二個參數的類型為自訂類型,要麼使用泛型 EventHandler 委託類並用自訂類型替代泛型型別參數。
39
40 myTimer.Elapsed += new System.Timers.ElapsedEventHandler(TimeEventHandler);
41 myTimer.Interval = 1000;
42 myTimer.Enabled = true;
43 //觸發事件
44 myEvent(this, new EventArgs());
45
46 }
47
48 //委託的方法
49 public void TimeEventHandler(object sender, System.Timers.ElapsedEventArgs e)
50 {
51 Console.Clear();
52 Console.Write("目前時間:"+ DateTime.Now.ToLocalTime());
53 }
54 }