- namespace 事件发布和订阅_2
- {
- class Program
- {
- static void Main(string[] args)
- {
- TrafficLight light = new TrafficLight();
- Car car1 = new Car();
- car1.Enter(light);
- light.ChangeColor(60);
- Console.ReadKey();
- }
- }
- public class LightEvrntArgs : EventArgs
- {
- private int seconds;
- public int Seconds { get { return seconds; } }
- public LightEvrntArgs(int seconds)
- {
- this.seconds = seconds;
- }
- }
- public class TrafficLight
- {
- private bool color = false;
- public bool Color { get { return color; } }
- public event EventHandler OnColorChange;
- public void ChangeColor(int seconds)
- {
- color = !color;
- Console.WriteLine(color ? "红灯亮" : "绿灯亮");
- if (OnColorChange != null)
- {
- OnColorChange(this, new LightEvrntArgs(seconds));
- }
- }
- }
- public class Car
- {
- private bool bRun = true;
- public void Enter(TrafficLight light)
- {
- light.OnColorChange += LightChange;
- }
- //相应的事件处理方法
- public virtual void LightChange(object sender, EventArgs e)
- {
- if (((TrafficLight)sender).Color)
- {
- bRun = false;
- Console.WriteLine("{0}停车{1}秒后启动", this, ((LightEvrntArgs)e).Seconds);
- }
- else
- {
- bRun = true;
- Console.WriteLine("{0}启动{1}秒后通过", this, ((LightEvrntArgs)e).Seconds);
- }
- }
- }
- }
复制代码 这个事件委托我似懂非懂,//相应的事件处理方法
public virtual void LightChange(object sender, EventArgs e)
这句我只知道相当于WinForm程序中的Button_Click(object sender, EventArgs e)
主要是事件发布者方TrafficLight的事件委托该如何理解????
|