C#事件與委託簡單實現

假設我們有個高檔的熱水器(Heater),我們給它通上電,當水溫超過95度的時候:1、揚聲器(Alarm)會開始發出語音,告訴你水的溫度;2、液晶屏(Display)也會改變水溫的顯示,來提示水已經快燒開了。

可以建立如下事件與委託(在控制檯下實現):

Heater.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    public class Heater
    {
        int temperature;
        public string bread = "007";
        public delegate void Handle(object obj,BoiledEventArgs e);
        public event Handle Boiled;

        public class BoiledEventArgs:EventArgs
        {
            public readonly int temperature;
            public BoiledEventArgs(int temperature)
            {
                this.temperature = temperature;
            }
        }

        protected virtual void OnBoiled(BoiledEventArgs e)
        {
            if (Boiled != null)
                Boiled(this, e);
        }

        public void BoilWater()
        {
            for (int i = 0; i <= 100; i++)
            {
                temperature = i;
                if (temperature > 95)
                {
                    if (Boiled != null)
                    {
                        BoiledEventArgs e = new BoiledEventArgs(temperature);
                        OnBoiled(e);
                    }
                }
            }
        }
    }
}

Display.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    public class Display
    {
        public static void ShowMsg(object obj,Heater.BoiledEventArgs e)
        {
            Heater heater = (Heater)obj;
            Console.WriteLine("{0}:警告:水已經{1}度了!!", heater.bread, e.temperature.ToString());
        }
    }
}

Alarm.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    public class Alarm
    {
        public void MakeAlert(object obj, Heater.BoiledEventArgs e)
        {
            Heater heater = (Heater)obj;
            Console.WriteLine("{0}:水已經{1}度了!", heater.bread, e.temperature.ToString());
        }
    }
}

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Heater heater = new Heater();
            Alarm alarm=new Alarm();
            heater.Boiled += alarm.MakeAlert;
            heater.Boiled += Display.ShowMsg;
            heater.BoilWater();
            Console.ReadKey();
        }
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章