IEnumerable、GetEnumerator、IEnumerator之间的…
2018-06-17 20:22:39来源:未知 阅读 ()
了解了这些也就明白了遍历的原理,晚安。
1 using System; 2 using System.Collections; 3 4 public class Person 5 { 6 public Person(string fName, string lName) 7 { 8 this.firstName = fName; 9 this.lastName = lName; 10 } 11 12 public string firstName; 13 public string lastName; 14 } 15 16 public class People : IEnumerable 17 { 18 private Person[] _people; 19 public People(Person[] pArray) 20 { 21 _people = new Person[pArray.Length]; 22 23 for (int i = 0; i < pArray.Length; i++) 24 { 25 _people[i] = pArray[i]; 26 } 27 } 28 29 IEnumerator IEnumerable.GetEnumerator() 30 { 31 return (IEnumerator) GetEnumerator(); 32 } 33 34 public PeopleEnum GetEnumerator() 35 { 36 return new PeopleEnum(_people); 37 } 38 } 39 40 public class PeopleEnum : IEnumerator 41 { 42 public Person[] _people; 43 44 // Enumerators are positioned before the first element 45 // until the first MoveNext() call. 46 int position = -1; 47 48 public PeopleEnum(Person[] list) 49 { 50 _people = list; 51 } 52 53 public bool MoveNext() 54 { 55 position++; 56 return (position < _people.Length); 57 } 58 59 public void Reset() 60 { 61 position = -1; 62 } 63 64 object IEnumerator.Current 65 { 66 get 67 { 68 return Current; 69 } 70 } 71 72 public Person Current 73 { 74 get 75 { 76 try 77 { 78 return _people[position]; 79 } 80 catch (IndexOutOfRangeException) 81 { 82 throw new InvalidOperationException(); 83 } 84 } 85 } 86 } 87 88 class App 89 { 90 static void Main() 91 { 92 Person[] peopleArray = new Person[3] 93 { 94 new Person("John", "Smith"), 95 new Person("Jim", "Johnson"), 96 new Person("Sue", "Rabon"), 97 }; 98 99 People peopleList = new People(peopleArray); 100 foreach (Person p in peopleList) 101 Console.WriteLine(p.firstName + " " + p.lastName); 102 103 } 104 } 105 106 /* This code produces output similar to the following: 107 * 108 * John Smith 109 * Jim Johnson 110 * Sue Rabon 111 * 112 */
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
上一篇:linq to sql简单使用
- IEnumerable,ICollection,IList接口问题 2018-06-17
- IList,ICollection,IEnumerable,IEnumerator,IQueryable 2018-06-17
- C# 索引器,实现IEnumerable接口的GetEnumerator()方法 2018-06-17
- 关于迭代器中IEnumerable与IEnumerator的区别 2018-06-17
- 如何选择使用IEnumerable, ICollection, IList 2018-06-17
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash