class Program
{
static void Main(string[] args)
{
TrafficLight Light = new TrafficLight();
Car car1 = new Car("car");
Ambulance Amb1 = new Ambulance("ambulance", true);
car1.Enter(Light);
Amb1.Enter(Light);
Light.ChangeColor(60);
Light.ChangeColor(60);
Console.ReadLine();
}
}
public delegate void EventHandler(object sender, EventArgs e);
public class LightEventArgs : EventArgs
{
private int seconds;
public int Seconds
{
get { return seconds; }
set { seconds = value; }
}
public LightEventArgs(int seconds)
{
this.seconds = seconds;
}
}
public class TrafficLight
{
private int color = 0;//0代表绿灯,1代表黄灯,2代表红灯,最开始是绿灯
public int Color
{
get { return color; }
set { color = value; }
}
public event EventHandler OnColorChange;
public void ChangeColor(int seconds)
{
if (color == 0)
{
seconds = 60;//绿灯的时间是60秒
Console.WriteLine("the light turns green");
color = 1;
}
else if(color==1)
{
seconds = 10;//黄灯的时间是10秒
Console.WriteLine("the light turns yellow");
color = 2;
}
else
{
seconds = 30;//红灯的时间是30秒
Console.WriteLine("the light turns red");
color = 0;
}
if (OnColorChange != null)
{
OnColorChange(this, new LightEventArgs(seconds));
}
}
}
public class Car
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private bool bRun = true;//小汽车正在行驶
public bool BRun
{
get { return bRun; }
set { bRun = value; }
}
public void Enter(TrafficLight Light)
{
Light.OnColorChange += LightColorChange;
}
public void Leave(TrafficLight Light)
{
Light.OnColorChange -= LightColorChange;
}
public virtual void LightColorChange(object sender, EventArgs e)
{
TrafficLight Light=new TrafficLight();
if (Light.Color == 0)
{
bRun = true;
Console.WriteLine("the {0} star,pass in {1} seconds", this, ((LightEventArgs)e).Seconds);
}
else if (Light.Color ==2)
{
bRun = true;
Console.WriteLine("the {0} stop,star after {1} seconds", this, ((LightEventArgs)e).Seconds);
}
else
{
bRun = true;
Console.WriteLine("the {0} accelerated,pass in {1} seconds", this, ((LightEventArgs)e).Seconds);
}
}
public Car(string name)
{
this.name = name;
}
public override string ToString()
{
return string.Format( name);
}
}
public class Ambulance : Car
{
private bool emergent = true;//救护车处于紧急状态
public bool Emergent
{
get { return emergent; }
set { emergent = value; }
}
public override void LightColorChange(object sender, EventArgs e)
{
TrafficLight Light = new TrafficLight();
if (Light.Color==2 && emergent)
{
Console.WriteLine("the {0} in an emergency,continue to drive", this);
}
else
{
base.Enter(Light);
}
}
public Ambulance(string name,bool emergent):base(name)
{
this.emergent=emergent;
}
}
在运行的时候出了问题,没有救护车,小汽车在黄灯的时候仍处于绿灯的状态,不知道问题出在了哪里,请大佬帮忙看看吧