C#委托_002

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

namespace CSharp_Learn_001
{
         //1. 热水器
         public class Heater{
                 private int temperature;
                 //1.1 声明委托
                 public delegate void BoilHandler( int param);
                 //1.2 声明事件
                 public event BoilHandler BoilEvent;

                 //1.3 烧水Action
                 public void BoilWater(){
                         for( int i=0; i<=100; i++){
                                temperature = i;
                        }

                         if(temperature > 95){
                                 //1.3.1 如果有对象注册
                                 if(BoilEvent != null){
                                         //1.3.2 调用所有注册对象的方法
                                        BoilEvent(temperature);
                                }
                        }
                }
        }

         //2. 警报器
         public class Alarm
        {
                 public void MakeAlert( int param)
                {
                        Console.WriteLine( "Alarm: 滴滴滴, 水已经{0}度了", param);
                }
        }
         //3. 显示器
         public class Display
        {
                 public static void ShowMsg( int param)
                {
                        Console.WriteLine( "Display: 水快烧开了,当前温度:{0}度.", param);
                }
        }

         class Program{
                 static void Main( string[] args){
                        Heater heater= new Heater();
                        Alarm alarm= new Alarm();
                         //注册方法
                        heater.BoilEvent += alarm.MakeAlert;
                        heater.BoilEvent += ( new Alarm()).MakeAlert;
                        heater.BoilEvent += Display.ShowMsg;

                        heater.BoilWater();

                        Console.ReadKey();
                }
        }
}


你可能感兴趣的:(C#,delegate,C#委托)