C#委託回撥的一個例子

pengfoo發表於2013-12-27

參考:

http://www.cnblogs.com/jimmyzhang/archive/2007/09/23/903360.html

直接上程式碼:

using System;
using System.Collections.Generic;
using System.Text;

namespace Delegate
{
   //加熱器
    public class Heater
    {
        private int tempurature;
        public delegate void BoilHandler(int param);
        public event BoilHandler Boilevent;

        public void BoilWater()
        {
            int i = 0;
            while (i < 100)
            {
                tempurature = i;
                if (tempurature > 95) 
                {
                    if (Boilevent!=null)
                    {
                        Boilevent(tempurature);
                    }
                }
                i++;
            }
        }
    }

    //顯示器
    public class Displayer
    {
        public void showMsg(int t)
        {
            Console.WriteLine("當前溫度是{0}度",t);
        }
    }

    //警報器
    public class Alarmer
    {
        public static void alam(int t)
        {
            Console.WriteLine("警告!溫度已經{0}度了,水即將燒開了!",t);
        }
    }

    public class Program
    {
        public static void Main()
        {
            Heater heater = new Heater();

            Displayer displayer = new Displayer();

            //註冊方法
            heater.Boilevent += displayer.showMsg;//註冊物件的方法

            heater.Boilevent += (new Displayer().showMsg);//註冊匿名物件方法

            heater.Boilevent += Alarmer.alam;//註冊靜態方法

            heater.BoilWater();

        }
    }
        
    
}



相關文章