国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

C#使用yield關鍵字構建迭代器詳解

2020-01-24 00:27:13
字體:
來源:轉載
供稿:網友

以前,如果我們希望構建支持foreach枚舉的自定義集合,只能實現IEnumerable接口(可能還有IEnumerator()),返回值還必須是IEnumerator類型,除此之外還可以通過迭代器來使用構建foreach循環的類型,詳細見下鏈接。

 代碼

 public class Car  {    //內部狀態數據    public int CurentSpeed;    public int MaxSpeed;    public string name;    //汽車能不能用    private bool carIsdead;    //類構造函數    public Car() { }    public Car(string name, int currentspeed, int maxspeed = 100)    {      this.name = name;      this.CurentSpeed = currentspeed;      this.MaxSpeed = maxspeed;    }    //定義委托類型    public delegate void CarEngineHandler(string msdForCar);    //定義每個委托類型的成員變量    private CarEngineHandler listOfhandlers;    //向調用者添加注冊函數    public void RegisterWithCarEngine(CarEngineHandler methodTocall)    {      if (listOfhandlers == null)        listOfhandlers = methodTocall;      else        listOfhandlers += methodTocall;//支持多路廣播    }    //實現Accelerate()方法    public void Accelerate(int delta)    {      if (carIsdead)      {        if (listOfhandlers != null)        {          listOfhandlers("sorry,this car is dead");        }      }      else      {        CurentSpeed += delta;        //不能超過最大速度        if (5 == (MaxSpeed - CurentSpeed) && listOfhandlers != null)        {          listOfhandlers("this speed is nearly to the maxspeed");        }        if (CurentSpeed > MaxSpeed)        {          carIsdead = true;        }        else          Console.WriteLine("current speed:{0}", CurentSpeed);      }    }  }  public class Garage : IEnumerable  {    private Car[] garage = new Car[3];    public Garage()    {      garage[0] = new Car("a", 10);      garage[1] = new Car("b", 13);      garage[2] = new Car("c", 14);    }    public Enumerator GetEnumerator()    {      //返回數組對象的IEnumerator      //return garage.GetEnumerator();      //用yield關鍵字構建迭代器方法      foreach (Car c in garage)      {        //當yield return語句執行后,當前位會被        //保存下來,下一次執行會從當前位開始        yield return c;      }    }  }  class Program  {    static void Main(string[] args)    {      Garage g = new Garage();      foreach (Car c in g)      {        Console.WriteLine("car name:{0}", c.name);      }    }  }

參考:C#中可枚舉類型詳解

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 日照市| 迁安市| 巴里| 那坡县| 齐齐哈尔市| 固镇县| 抚顺县| 喀喇沁旗| 团风县| 漯河市| 琼中| 珲春市| 黔东| 湖州市| 仙游县| 西峡县| 永嘉县| 永胜县| 彭山县| 友谊县| 铜鼓县| 于田县| 英山县| 天门市| 定南县| 达孜县| 西乌珠穆沁旗| 宣恩县| 大悟县| 大竹县| 北碚区| 北海市| 茶陵县| 平泉县| 吉木乃县| 大同县| 罗平县| 星子县| 蓬溪县| 康保县| 北辰区|