当前位置:编程学习 > C#/ASP.NET >>

简单C#事件示例

本文用事件模拟一个热水器烧水的过程,差不多是这样的:

热水器开始对水加热,当水加热到95度以上的时候,热水器的报警器开始报警,并且在屏幕上显示当前的水温。

不难从上面的这一小段话看到,要想模拟该程序,需要一个热水器对象Heater,报警器对象Alarm,显示器对象Display。

下面边上代码边解释吧。

   

/// <summary>
    /// 热水器类,用来烧水的
    /// </summary>
    class Heater
    {
        private int temperature;                    //水温
        public delegate void BoilEventHandler(object sender, BoilEventArgs e);
        public event BoilEventHandler boil;         //自定义事件

        public void OnBoil(BoilEventArgs e)         //水温达到一定温度后开始执行事件
        {
            if (boil != null)
                boil(this, e);
        }

        public void BoilWater()                     //水从0度开始烧,当达到95度的时候开始报警
        {
            for (int i = 0; i <100; i++)
            {
                temperature = i;
                if (temperature >= 95)
                {
                    BoilEventArgs e = new BoilEventArgs(temperature);
                    OnBoil(e);
                }
            }
        }
    }

 

/// <summary>
    /// 自定义事件参数,此类必须继承EventArgs类
    /// </summary>
    class BoilEventArgs:EventArgs
    {
        public readonly int temperature;            //水温

        public BoilEventArgs(int temperature)
        {
            this.temperature = temperature;
        }
    }

 

/// <summary>
    /// 警报器类,当水温达到一定程度时,发出声响提示用户水已开
    /// </summary>
    class Alarm
    {
        public void MakeAlarm(object sender, BoilEventArgs e)
        {
            Console.WriteLine(string.Format("警报:嘟嘟,水温{0}度", e.temperature.ToString()));
        }
    }

 

/// <summary>
    /// 显示器类,当水温达到一定程度时,在屏幕上显示当前温度给用户看
    /// </summary>
    class Display
    {
        public static void ShowMessage(object sender,BoilEventArgs e)
        {
            Console.WriteLine(string.Format("屏幕显示:当前温度{0}度",e.temperature.ToString()));
        }
    }

 

class Program
    {
        static void Main(string[] args)
        {
            Heater heater = new Heater();
            Alarm alarm = new Alarm();
            heater.boil += alarm.MakeAlarm;
            heater.boil += Display.ShowMessage;
            heater.BoilWater();
            Console.ReadLine();
        }
    }

 

输出结果:

    
补充:软件开发 , C# ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,