C#委托和事件例子

本文介绍了一个热水器温度警报系统的模拟实现。系统包含加热、显示和警报三部分,当水温达到95度时,通过定义委托和事件,触发显示和声音警报。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

    一个热水器包括加热水的部分heater、显示屏提示部分display和发出声音报警部分alert,

要求当热水器加热水到95度以上时,display和alert部分都需要分别以各自的方式发出警报。

编程模拟这个过程。

在这里我定义三个类:heater,display和alert;框架结构图如下图所示:

 

 

 

 

 

 

 

 

 

在heater中,定义委托和事件,并将其绑定在一起,其内容如下:

public delegate void boiledhandler(int temp); //定义一个委托(等同于一个类)

    class Heater

    {

        private int temperature;

        public event boiledhandler OnBoiled;      //定义一个事件,并绑定委托;

        public void BoiledWater()                 //方法

        {

            for (int i = 0; i <= 100; i++)

            {

                temperature = i;

                if (temperature >= 95)

                {

                    OnBoiled(temperature);         //事件触发函数

                }

            }

 

        }

    }

在display类中,其主要定义显示的方法:

             class Display

    {

        public void DispTemp(int temp)

        {

            Console.WriteLine("现?在¨²水?温?:êo" + temp);

        }

 

    }

         在alert类中定义方法:

class Alert

    {

        public void AlertTemp(int temp)

        {

            Console.WriteLine("嘀¤?嘀¤?嘀¤?,ê?水?温?" + temp + ",快¨¬开a啦¤2!ê?");

        }

    }

         在主函数中调用如下:

 class Program

    {

        static void Main(string[] args)

        {

            Heater h = new Heater();

            Display d = new Display();

            Alert a = new Alert();

            h.OnBoiled += d.DispTemp;   //事件注册

            h.OnBoiled += a.AlertTemp;  //事件注册

            h.BoiledWater();

            Console.ReadKey();

        }

}

运行结果如下所示:

转载于:https://www.cnblogs.com/qingfengshuimu/p/3451102.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值