编辑代码

using System;
using System.IO;

namespace BoilerEventAppl
{

    //boiler类

    class Boiler
    {
        private int temp;
        private int pressure;
        public Boiler(int t, int p)
        {
            temp = t;
            pressure = p;
        }

        public int getTemp()
        {
            return temp;
        }
        public int getPressure()
        {
            return pressure;
        }
    }

    //事件发布器

    class DelegateBoilerEvent  //DelegateBoilerEvent = 委托锅炉事件
    {
        public delegate void BoilerLogHandler(string status);

        //基于上面的委托定义事件

        public event BoilerLogHandler BoilerEventLog;

        public void LogProcess()
        {
            string remarks = "O.K";
            Boiler b = new Boiler(100,12);
            int t = b.getTemp();
            int p = b.getPressure();
            if(t > 150 || t < 80 || p < 12 || p > 15)
            {
                remarks = "需要维护";
            }

            OnBoilerEventLog("日志记录信息:\n");
            OnBoilerEventLog("温度:" + t + "\n压力: " + p);
            OnBoilerEventLog("\n消息: " + remarks);
        }

        protected void OnBoilerEventLog(string message)
        {
            if(BoilerEventLog != null)
            {
                BoilerEventLog(message);
            }
        }
    }

    //该类保留写入日志文件的条款

    class BoilerInfoLogger  //BoilerInfoLogger = 锅炉信息记录器
    {
        FileStream fs;
        StreamWriter sw;
        public BoilerInfoLogger(string filename)
        {
            fs = new FileStream(filename, FileMode.Append, FileAccess.Write);
            sw = new StreamWriter(fs);
        }

        public void Logger(string info)
        {
            sw.WriteLine(info);
        }

        public void Close()
        {
            sw.Close();
            fs.Close();
        }
    }

    //事件订阅器

    public class RecordBoilerInfo   //RecordBoilerInfo = 记录锅炉信息
    {
        static void Logger(string info)
        {
            Console.WriteLine(info);
        }

        //Logger = 记录   记录结束

        static void Main(string[] args)
        {
            BoilerInfoLogger filelog = new BoilerInfoLogger("e:\\boiler.txt");
            DelegateBoilerEvent BoilerEvent = new DelegateBoilerEvent();
            BoilerEvent.BoilerEventLog += new DelegateBoilerEvent.BoilerLogHandler(Logger);
            BoilerEvent.BoilerEventLog += new DelegateBoilerEvent.BoilerLogHandler(filelog.Logger);
            BoilerEvent.LogProcess();
            Console.ReadLine();
            filelog.Close();
        }  //end of main
    }   //结束记录锅炉信息
}