其中 IsDead是表示車子是否已經報廢了。下面是一個加速的方法:
public void Accelerate(int addSpeed)
{
if (IsDead)
{
if (this.Exploded!= null)
Exploded("The Car Is Dead");
}
else
{
CurrSpeed += addSpeed;
if (10 == MaxSpeed - CurrSpeed &&AbortToBlow != null)
{
AbortToBlow("Careful!Bona blow!");
}
if (CurrSpeed >= MaxSpeed)
IsDead = true;
else
Console.WriteLine("CurrentSpeed:{0}", CurrSpeed);
}
}
完整代碼:
public class EventCar
{
public delegate void CarEventHandler(string msg);
public event CarEventHandler AbortToBlow;
public event CarEventHandler Exploded;
private const int MaxSpeed = 180;
public int CurrSpeed { get; private set; }
public bool IsDead { get; private set; }
public string Name { get; private set; }
public EventCar() { }
public EventCar(string carName, int currSpeed)
{
if (currSpeed > MaxSpeed)
IsDead = true;
else
{
Name = carName;
CurrSpeed = currSpeed;
}
}
public void Accelerate(int addSpeed)
{
if (IsDead)
{
if (this.Exploded!= null)
Exploded("The Car Is Dead");
}
else
{
CurrSpeed += addSpeed;
if (10 == MaxSpeed - CurrSpeed &&AbortToBlow != null)
{
AbortToBlow("Careful!Bona blow!");
}
if (CurrSpeed >= MaxSpeed)
IsDead = true;
else
Console.WriteLine("CurrentSpeed:{0}", CurrSpeed);
}
}
}