本文参考了鹏哥的c#视频教学,在此谢过!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using 烧水;
namespace 委托和事件
{
public delegate void Greeting(string name);
class Program
{
public static void ChineseGreeting(string name)
{
Console.WriteLine("早上好:" + name);
}
public static void EnglishGreeting(string name)
{
Console.WriteLine("Morning:" + name);
}
static void Main(string[] args)
{
//heater heat = new heater();
//alarm alert = new alarm();
//display disp = new display();
//heat.BoilEvent += alert.MakeAlert;
//heat.BoilEvent += disp.ShowMsg;
//heat.BoilWater();
Greeting greet = new Greeting(ChineseGreeting);
greet += EnglishGreeting;
greet("tom");
}
}
}
namespace 烧水
{
public class heater
{
private int temperature = 0;
public delegate void BoilHandler(int param);//定义一个委托
public event BoilHandler BoilEvent;//定义事件
public void BoilWater()
{
for (int i = 0; i <=100; i++)
{
temperature++;
if (i >=99 && BoilEvent != null)
{
BoilEvent(--temperature);
return;
}
}
}
}
public class alarm
{
public void MakeAlert(int param)
{
Console.WriteLine("响铃:水快开了,当前温度:" + param.ToString());
}
}
public class display
{
public void ShowMsg(int param)
{
Console.WriteLine("显示当前温度为:" + param.ToString());
}
}
}