=================================================簡(jiǎn)單的實(shí)現(xiàn)IEnumerable接口
目前創(chuàng)新互聯(lián)建站已為成百上千家的企業(yè)提供了網(wǎng)站建設(shè)、域名、虛擬主機(jī)、綿陽(yáng)服務(wù)器托管、企業(yè)網(wǎng)站設(shè)計(jì)、樂(lè)亭網(wǎng)站維護(hù)等服務(wù),公司將堅(jiān)持客戶導(dǎo)向、應(yīng)用為本的策略,正道將秉承"和諧、參與、激情"的文化,與客戶和合作伙伴齊心協(xié)力一起成長(zhǎng),共同發(fā)展。
------------------------------------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];//實(shí)例化長(zhǎng)度為三個(gè)的數(shù)組 public PerAll()//構(gòu)造函數(shù)初始化數(shù)組 { p[0] = new Person { Name = "張三" }; p[1] = new Person { Name = "李四" }; p[2] = new Person { Name = "王五" }; } public IEnumerator GetEnumerator()//迭代器 { return p.GetEnumerator();//直接調(diào)用數(shù)組自帶的的GetEnumerator。(簡(jiǎn)單委托請(qǐng)求到System.Array) } } }
------------------------------------主程序
PerAll p = new PerAll();//實(shí)例化對(duì)象 //-------------------第一種方式遍歷 foreach (Person item in p) { Console.WriteLine(item.Name); } //-------------------第二中方式遍歷 IEnumerator ie = p.GetEnumerator(); while (ie.MoveNext()) { Console.WriteLine((ie.Current as Person).Name); } //普通數(shù)組遍歷 string[] str = new string[3] { "張遼", "張合", "張飛" }; IEnumerator strie = str.GetEnumerator(); while (strie.MoveNext()) { Console.WriteLine(strie.Current as string); }