1、新建一個(gè)控制臺(tái)應(yīng)用程序TestDelegate,本項(xiàng)目主要實(shí)現(xiàn):熱水器加熱,報(bào)警器監(jiān)控,當(dāng)熱水溫度達(dá)到80度的時(shí)候報(bào)警器報(bào)警這樣一個(gè)簡(jiǎn)單的事件處理程序
// 如果加熱,則引發(fā)事件
public class 熱水器
{
// 先定義一個(gè)事件,這個(gè)事件表示“熱水器”在加熱。
public event PlayGameHandler PlayGame;
public 熱水器()
{
Console.WriteLine("生成熱水器....");
}
public void 加熱()
{
Console.WriteLine("開始加熱了.....");
System.EventArgs e = new EventArgs();
for (int i = 1; i 101;i++)//溫度每增加一度調(diào)觸發(fā)一次事件
{
System.Threading.Thread.Sleep(100);//休息0.1秒
Console.WriteLine(i.ToString()+"度");
if (PlayGame != null)
{
if(i>=80)//當(dāng)溫度大于80度
PlayGame(this, e);//觸發(fā)事件
}
}
}
}
public class Program
{
//[STAThread]
public static void Main(string[] args)
{
Console.WriteLine("場(chǎng)景開始了....");
報(bào)警器 w = new 報(bào)警器();
熱水器 z = new 熱水器();
// 指定監(jiān)視
z.PlayGame += new PlayGameHandler(w.報(bào)警);
System.Threading.Thread.Sleep(1000);
// 開始加熱
z.加熱();
Console.WriteLine("場(chǎng)景結(jié)束...");
Console.ReadLine();
}
}