標籤:
事件和委託極為的相似。其實,事件就好像被簡化的針對特殊用途的委託。
1,發行者定義時間成員。
2,訂閱者註冊在事件成員被觸發時要調用的方法。
3,當發行者觸發事件時,所有列表註冊的事件都將被調用。
下面我們來看一個簡單的例子:
EventHandler是.Net BCL使用預定義的用於標準時間的委託,
public delegate void EventHandler(object sender,EventArgs e)
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace EventHandlerTest{ class Program { //委託 public delegate void EventHandler(string a); //事件 public static event EventHandler SetCode; static void Main(string[] args) { //註冊 Program.SetCode += GetCode; //觸發 if (SetCode != null) //檢查是否有事件註冊 { SetCode("觸發"); } //取消 Program.SetCode -= GetCode; Console.ReadLine(); } public static void GetCode(string s) { Console.WriteLine(s); } }}
我們來看另外一個例子:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks;namespace TestEvent1{ public class MyTimeClass { public event EventHandler Elapsed; //聲明事件 public void OnOneSecond(object source, EventArgs args) { if (Elapsed != null) { Elapsed(source,args); } } private System.Timers.Timer MyPrivateTimer;//私人計時器
public MyTimeClass() { MyPrivateTimer = new System.Timers.Timer(); //建立私人計時器 MyPrivateTimer.Elapsed += OnOneSecond; //附加事件處理常式 MyPrivateTimer.Interval = 1000; MyPrivateTimer.Enabled = true; } } class classA { public void TimerHandlerA(object source, EventArgs args) { Console.WriteLine("****************************"); Console.WriteLine("ClassA EventHandler called"); } } class classB { public static void TimerHandlerB(object source, EventArgs args) { Console.WriteLine("ClassB EventHandler called"); Console.WriteLine("****************************"); } } class Program { static void Main(string[] args) { classA ca = new classA(); MyTimeClass mtc = new MyTimeClass(); mtc.Elapsed += ca.TimerHandlerA; mtc.Elapsed += classB.TimerHandlerB; Thread.Sleep(2000); Random random = new Random(); while (true) { int tmp = random.Next(1,3); switch (tmp) { case 1: mtc.Elapsed -= ca.TimerHandlerA; Console.WriteLine("ClassA Handler Cancled"); mtc.Elapsed += ca.TimerHandlerA; break; case 2: mtc.Elapsed -= classB.TimerHandlerB; Console.WriteLine("ClassB Handler Cancled"); mtc.Elapsed += classB.TimerHandlerB; break; default: break; } Thread.Sleep(2000); } } }}
運行結果:
PS:事件驅動的建立
private System.Timers.Timer MyPrivateTimer; //聲明私人計時器變數
MyPrivateTimer = new System.Timers.Timer(); //建立私人計時器MyPrivateTimer.Elapsed += OnOneSecond; //附加事件處理常式MyPrivateTimer.Interval = 1000; //設定事件間隔MyPrivateTimer.Enabled = true; //啟用
C# 事件