// 如果加熱,則引發事件
public class 熱水器
{
// 先定義一個事件,這個事件表示“熱水器”在加熱。
public event PlayGameHandler PlayGame;
public 熱水器()
{
Console.WriteLine("生成熱水器....");
}
public void 加熱()
{
Console.WriteLine("開始加熱了.....");
System.EventArgs e = new EventArgs();
for (int i = 1; i 101;i++)//溫度每增加一度調觸發一次事件
{
System.Threading.Thread.Sleep(100);//休息0.1秒
Console.WriteLine(i.ToString()+"度");
if (PlayGame != null)
{
if(i>=80)//當溫度大于80度
PlayGame(this, e);//觸發事件
}
}
}
}
public class Program
{
//[STAThread]
public static void Main(string[] args)
{
Console.WriteLine("場景開始了....");
報警器 w = new 報警器();
熱水器 z = new 熱水器();
// 指定監視
z.PlayGame += new PlayGameHandler(w.報警);
System.Threading.Thread.Sleep(1000);
// 開始加熱
z.加熱();
Console.WriteLine("場景結束...");
Console.ReadLine();
}
}