测速_C#之委托示例:水壶 报警器 显示器

更新时间:2020-04-01    来源:显示器    手机版     字体:

【www.bbyears.com--显示器】

Delegate 是一种用于封装命名或匿名方法的应用类型。

委托用于将方法作为参数传递给其他方法。


.net framework 中关于委托的编码规范:

1 委托类型的名称都应该以 EventHandler 结束。

2 委托类型的原型定义:有一个void返回值,接受两个参数: 一个 object ,第二个 EventArgs(或继承自它)

3 事件的命名 为 委托去掉 EventHandler 剩余部分

4 继承自 EventHandler 的类型应该以 EventArgs 结尾

 

C# 委托面试题:

1、热水壶负责烧水,当水温大于95摄氏度时,报警器报警,同时显示器显示水温度。

2、可扩展性

3、低耦合


代码如下:

 public class Test_delegate11
    {
        ///


        /// 水壶类,负责烧水
        ///

        public class Heater
        {
            public readonly string ID="1001" ; //水壶的附加属性
            public readonly string Area="山东济南";
            
            public delegate void BoilHeaterEventHandler(object sender, BoilEventArgs e); //定义委托
            public event BoilHeaterEventHandler BoilHeater; //事件
            ///
            /// 参数类,存储温度
            ///

            public class BoilEventArgs : EventArgs
            {
                public int Temp { get; set; }
                public BoilEventArgs(int i)
                {
                    this.Temp = i;
                }
            }
            public virtual void OnBoild(BoilEventArgs e)
            {
                if (BoilHeater != null)
                {
                    BoilHeater(this, e); //执行注册到事件对象的所有方法
                }
            }
            ///
            /// 加火 烧水
            ///

            public void BoildWater()
            {
                for (int i = 50; i <= 100; i++)
                {
                    if (i >= 95) //大于95度,开始执行事件,事件将被注册有2个方法(报警 和 显示)
                    {
                        OnBoild(new BoilEventArgs(i));
                    }
                }
            }
        }
        
        ///
        /// 报警器,负责鸣警
        ///

        public class Alarm
        {
            public static void MakeAlarm(object sender, Heater.BoilEventArgs e) //报警
            {
                Heater _heater = (Heater)sender;
                Console.WriteLine("编号为" + _heater.ID + "的水壶高温告警。");
            }
        }
        ///
        /// 显示器,负责显示当前水温
        ///

        public class Display
        {
            public static void MakeDisplay(object sender, Heater.BoilEventArgs e) //显示
            {
                Heater _heater = (Heater)sender;
                Console.WriteLine("编号为" + _heater.ID + "的水壶水温:" + e.Temp.ToString() + " 摄氏度\n");
            }
        }
        public void main() //主调用方法,程序启动
        {
            Heater heater = new Heater();
            heater.BoilHeater += Alarm.MakeAlarm; //注册 报警器的报警方法
            heater.BoilHeater += Display.MakeDisplay; //注册 显示器的显示方法
            heater.BoildWater(); //努力的烧水
        }
    }


 new Test_delegate11().main(); //执行


结果:

本文来源:http://www.bbyears.com/bangongshuma/91209.html

热门标签

更多>>

本类排行