程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> C#3.0筆記(二)預備知識之委托與事件(2)

C#3.0筆記(二)預備知識之委托與事件(2)

編輯:關於C語言

其中 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);
      }
    }

  }

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved