首先,先說明事件跟委托的關系,事件并不等于委托,事件等于委托鍊。
C#中處理事件的六個步驟:
1、聲明事件所需的代理;
2、事件的聲明;
3、定義觸發事件的方法;
4、訂閱者定義事件處理程式;
5、向事件發行者訂閱一個事件;
6、觸發事件。
根據上面六個步驟,寫出一個事件的過程,代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestEvent
{
class RichMan //老闆
{
public delegate void TreasurerSendMoney(); //1、聲明老闆發工資事件所需的代理-"财務員發工資"
public event TreasurerSendMoney OnSendMoney; //2、聲明财務員發工資事件
public void sendMoneyTimeOut() //3、觸發财務員發工資的方法
{
if (OnSendMoney != null)
{
Console.WriteLine("親,開始發工資啦!");
OnSendMoney();
Console.WriteLine("火熱發送工資中...");
}
}
}
class PoorMan //勞工
{
public void TakeMoney() //4、勞工拿到工資之後的處理方法
{
Console.WriteLine("我終于拿到工資啦!!!明天有錢旅遊啦!!!");
}
}
class Program
{
static void Main(string[] args)
{
RichMan richMan = new RichMan();
PoorMan poorMan = new PoorMan();
richMan.OnSendMoney += new RichMan.TreasurerSendMoney(poorMan.TakeMoney); //5、将勞工拿工資之後的處理方法綁定到老闆發工資的事件中
richMan.sendMoneyTimeOut(); //6、觸發發工資事件的方法
Console.ReadLine();
}
}
}
運作程式,可以看到如下輸出:
親,開始發工資啦!
我終于拿到工資啦!!!明天有錢旅遊啦!!!
火熱發送工資中...
源碼連結:http://download.csdn.net/detail/scrystally/5763405