0
点赞
收藏
分享

微信扫一扫

C# 理解委托与事件

乐百川 2022-01-07 阅读 74

例子背景

假设我们有个高档的热水器,我们给它通上电,当水温超过95度的时候:1、扬声器会开始发出语音,告诉你水的温度;2、液晶屏也会改变水温的显示,来提示水已经快烧开了。

现在我们需要写个程序来模拟这个烧水的过程,我们将定义一个类来代表热水器,我们管它叫:Heater,它有代表水温的字段,叫做temperature;当然,还有必不可少的给水加热方法BoilWater(),一个发出语音警报的方法MakeAlert(),一个显示水温的方法,ShowMsg()。

    public class Heater
    {
        private int temperature;
        public delegate void BoilHandler();//事件的委托
        public event BoilHandler BoilEvent;//事件
        public void Boilwater()
        {
            for (int i = 0; i <= 100; i++)
            {
                temperature = i;
                if (temperature > 96)
                {
                    if (BoilEvent != null)
                    {
                        BoilEvent();//引发事件
                    }
                }
            }
        }
        public void Makealter()
        {
            Console.WriteLine("Alarm:嘀嘀嘀,水已经{0}度了", temperature);

        }

        public void ShoeMSG()
        {
            Console.WriteLine("Display:水快烧开了,当前温度:", temperature);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Heater ht = new Heater();
            ht.BoilEvent += ht.Makealter;//给alarm的makealert方法订阅事件
            ht.BoilEvent += ht.ShoeMSG;//订阅静态方法
            ht.Boilwater();//烧水,会自动调用订阅过的对象方法
            Console.ReadKey();
        }
    }
举报

相关推荐

0 条评论