標籤:line pac 類型 執行 strong char int button body
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,否則就是泛型介面的型別參數。
除聲明外,
跑步客文章均為原創,轉載請以連結形式標明本文地址
C#中的IEnumerable簡介及簡單實現執行個體
本文地址: http://www.paobuke.com/develop/c-develop/pbk23109.html
相關內容C#.Net基於Regex抓取百度百家文章列表的方法樣本C#串連MySQL的兩個簡單程式碼範例C# MVC 支付教程系列之掃碼支付代碼執行個體C#êμ?????aêμó?μ?SQLhelper
C#通過Semaphore類控制線程隊列的方法C#實現的json序列化和還原序列化代碼執行個體C#中timer定時器用法執行個體C#實現為類和函數代碼自動添加著作權注釋資訊的方法
C#中的IEnumerable簡介及簡單實現執行個體