C#處理事件的過程


首先,先說明事件跟委託的關係,事件並不等於委託,事件等於委託鏈。

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







發佈了26 篇原創文章 · 獲贊 8 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章