第3章 C#中的委托和事件

时间:2023-12-21 20:09:14

.NET框架中的委托和事件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Text.RegularExpressions; namespace _.net之美
{
class Program
{
static void Main(string[] args)
{
Heater heater = new Heater();
Alert alert = new Alert();
heater.boiled += alert.AlertTemperature;
heater.boiled += Display.ShowMsg;
heater.BoilWater();
Console.ReadKey();
}
} public class Heater
{
private readonly string area="ChengDu";
public string Area { get { return area; } } private readonly string type = "";
public string Type { get { return type; } } private int temperature; public delegate void BoiledEventHandle(object sender, BoiledEventArgs args);
public event BoiledEventHandle boiled; public void BoilWater()
{
for (int i = ; i <= ; i++)
{
temperature = i;
BoiledEventArgs e = new BoiledEventArgs(temperature);
if (temperature > )
{
OnBoiled(e);
}
}
} private void OnBoiled(BoiledEventArgs e)
{
if (boiled != null)
boiled(this, e);
} public class BoiledEventArgs
{
private readonly int temperature;
public BoiledEventArgs(int temperature)
{
this.temperature = temperature;
} public int Temperature { get { return this.temperature; } }
}
} public class Alert
{
public void AlertTemperature(object sender, Heater.BoiledEventArgs e)
{
Heater heater = (Heater)sender;
Console.WriteLine("Area:{0},Type:{1}", heater.Area, heater.Type);
Console.WriteLine("水快烧开了!");
}
} public class Display
{
public static void ShowMsg(object sender, Heater.BoiledEventArgs e)
{
Heater heater = (Heater)sender;
Console.WriteLine("Area:{0},Type:{1}", heater.Area, heater.Type);
Console.WriteLine("当前温度:{0}", e.Temperature);
}
}
}

委托进阶