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

首頁 > 編程 > C# > 正文

C#中的IEnumerable簡介及簡單實現實例

2020-01-24 02:07:47
字體:
來源:轉載
供稿:網友

IEnumerable這個接口在MSDN上是這么說的,它是一個公開枚舉數,該枚舉數支持在非泛型集合上進行簡單的迭代。換句話說,對于所有數組的遍歷,都來自IEnumerable,那么我們就可以利用這個特性,來定義一個能夠遍歷字符串的通用方法.

下面先貼出code.

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Collections; namespace mycs{  class Program  {    static void Main(string[] args)    {      charlist mycharlist = new charlist("hello world");      foreach (var c in mycharlist)      {        Console.Write(c);      }     Console.ReadLine();    }  }   class charlist : IEnumerable  {    public string TargetStr { get; set; }     public charlist(string str)    {      this.TargetStr = str;    }    public IEnumerator GetEnumerator()    {      //c# 1.0      return new CharIterator(this.TargetStr);      //c# 2.0      /*      for (int index = this.TargetStr.Length; index > 0;index-- )      {        yield return this.TargetStr[index - 1];      }       */    }  }  class CharIterator : IEnumerator  {    public string TargetStr { get; set; }    public int position { get; set; }     public CharIterator(string targetStr)    {      this.TargetStr = targetStr;      this.position = this.TargetStr.Length;    }    public object Current    {      get      {        if (this.position==-1||this.position==this.TargetStr.Length)        {          throw new InvalidOperationException();        }        return this.TargetStr[this.position];      }    }    public bool MoveNext()    {      if (this.position!=-1)      {        this.position--;      }      return this.position > -1;    }    public void Reset()    {      this.position = this.TargetStr.Length;    }  }}


在上面的例子c# 1.0中,CharIterator就是迭代器的實現,position字段存儲當前的迭代位置,通過Current屬性可以得到當前迭代位置的元素,MoveNext方法用于更新迭代位置,并且查看下一個迭代位置是不是有效的。

當我們通過VS單步調試下面語句的時候:

復制代碼 代碼如下:

foreach (var c in charList)

代碼首先執行到foreach語句的charList處獲得迭代器CharIterator的實例,然后代碼執行到in會調用迭代器的MoveNext方法,最后變量c會得到迭代器Current屬性的值;前面的步驟結束后,會開始一輪新的循環,調用MoveNext方法,獲取Current屬性的值。

通過C# 1.0中迭代器的代碼看到,要實現一個迭代器就要實現IEnumerator接口,然后實現IEnumerator接口中的MoveNext、Reset方法和Current屬性。

在C# 2.0中可以直接使用yield語句來簡化迭代器的實現。

如上面public IEnumerator GetEnumerator()方法中注釋掉的部分。
通過上面的代碼可以看到,通過使用yield return語句,我們可以替換掉整個CharIterator類。

yield return語句就是告訴編譯器,要實現一個迭代器塊。如果GetEnumerator方法的返回類型是非泛型接口,那么迭代器塊的生成類型(yield type)是object,否則就是泛型接口的類型參數。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 故城县| 东至县| 五河县| 正安县| 梅州市| 剑川县| 钦州市| 云霄县| 内丘县| 临泽县| 永定县| 岳阳县| 伊宁市| 靖安县| 东乡族自治县| 漳浦县| 惠来县| 固镇县| 林甸县| 桐庐县| 凤凰县| 柘城县| 婺源县| 花莲县| 苗栗县| 涟源市| 清徐县| 莫力| 凤山县| 县级市| 宜阳县| 阳城县| 大渡口区| 会东县| 海伦市| 珲春市| 克什克腾旗| 百色市| 阿尔山市| 隆回县| 神木县|