=================================================簡單的實現IEnumerable接口
------------------------------------Person.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections; namespace ConsoleApplication6 { public class Person { public string Name { get; set; } } }
------------------------------------PerAll.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections; namespace ConsoleApplication6 { public class PerAll:IEnumerable { Person[] p = new Person[3];//實例化長度為三個的數組 public PerAll()//構造函數初始化數組 { p[0] = new Person { Name = "張三" }; p[1] = new Person { Name = "李四" }; p[2] = new Person { Name = "王五" }; } public IEnumerator GetEnumerator()//迭代器 { return p.GetEnumerator();//直接調用數組自帶的的GetEnumerator。(簡單委托請求到System.Array) } } }
------------------------------------主程序
PerAll p = new PerAll();//實例化對象 //-------------------第一種方式遍歷 foreach (Person item in p) { Console.WriteLine(item.Name); } //-------------------第二中方式遍歷 IEnumerator ie = p.GetEnumerator(); while (ie.MoveNext()) { Console.WriteLine((ie.Current as Person).Name); } //普通數組遍歷 string[] str = new string[3] { "張遼", "張合", "張飛" }; IEnumerator strie = str.GetEnumerator(); while (strie.MoveNext()) { Console.WriteLine(strie.Current as string); }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。