using System;
public class Events
...{ static void Main()
...{ long speed;
CheckSpeed myCheckSpeed=new CheckSpeed();//檢查速度的類實例
DoSomeThing myDoSomeThing = new DOSomeThing();//生成提示降速類
Console.Write("目前行車速度:");
speed = long.Parse(Console.ReadLine());//輸入行車速度
Console.WriteLine("");//下行委托指定給檢查速度的事件 myEvent到myDOSomeThing.SlowDown
DefaultEvents myDefaultEvent = new DefaultEvents();
myCheckSpeed.myEvent += new SpeedCheckHandler(myDefaultEvent.DefaultEvent);
myCheckSpeed.myEvent += new SpeedCheckHandler(myDOSomeThing.SlowDown);
myCheckSpeed.myEvent += new SpeedCheckHandler(myDOSomeThing.DoRecord);//新增加一個委托到觸發事件的列表
myCheckSpeed.CheckSpeedLimit(speed);//具有委托事件的類的方法,調用此方法就會觸發事件myEvent
Console.ReadLine();
}
}
public class SpeedCheckEventArgs : EventArgs//類CheckSpeed事件的一個參數類
...{ private long speed;//事件參數e
public SpeedCheckEventArgs(long speed) ...{ this.speed = speed; }
public long getSpeed ...{ get ...{ return speed; } }
public string WarningMessage ...{ get ...{ return ("警告:行車超過速度界限!!"); } }
}
//--------------------------聲明委托--------------------------------------
public delegate void SpeedCheckHandler(object sender,SpeedCheckEventArgs e);
public class CheckSpeed//事件參數來源sender
...{ //-----------------聲明事件其定義在SlowDown----------------------
public event SpeedCheckHandler myEvent;
public void CheckSpeedLimit(long speed)//觸發事件的方法
...{ if (speed > 60)
...{ //產生事件參數e實例
SpeedCheckEventArgs speedsArgs = new SpeedCheckEventArgs(speed);
myEvent(this, speedsArgs);//觸發類事件調用SlowDown
}
else Console.WriteLine("您目前的速度正常.");
}
}
public class DOSomeThing//超速事件的類
...{ public void SlowDown(object sender, SpeedCheckEventArgs e)//事件的實現相當於onClick的實現
...{ Console.WriteLine(e.WarningMessage);
Console.WriteLine("您目前的速度{0}已經超速,請降低油門,降低速度,避免危險!!",e.getSpeed);
Console.WriteLine("正常的行車速度請降至60km/h!");
}
//記錄事件
public void DoRecord(object sender, SpeedCheckEventArgs e)
...{
Console.WriteLine("您的超速已被記錄,請到海潮路公路局繳納罰款!!速度:{0}km/h.",e.getSpeed);
}
}
public class DefaultEvents
...{ //自己補充一個事件
public void DefaultEvent(object sender, SpeedCheckEventArgs e) ...{ Console.WriteLine("超速沒有處理."); }
}