- IEnumerable接口的一個簡單示例
- 2012-04-02
0 個評論
-
收藏
我要投稿
-
IEnumerable接口是實現(xiàn)foreach循環(huán)的一個重要的接口,像數(shù)組,、集合等之所以可以用foreach循環(huán)遍歷其中的每個元素便是因為他們都實現(xiàn)了IEnumerable接口而,,那么這個接口到底是如何運行的呢,通過下面一個例子可以得到一些啟發(fā),。
定義一個這樣簡單的類:
01.public class Person
02. {
03. private string[] names= new string[] { "A", "B", "C" };
04. }
由于names屬性是私有屬性,,所以無法通過Person類的對象對其進行訪問,也就無法對其遍歷,,可以讓Person類實現(xiàn)IEnumerable接口來對其進行遍歷,,實現(xiàn)接口后的類如下:
01.public class Person : IEnumerable
02. {
03. private string[] names= new string[] { "A", "B", "C" };
04.
05. public IEnumerator GetEnumerator()
06. {
07.
08. }
09. }
可以看到實現(xiàn)了IEnumerable接口后Person類里面必須實現(xiàn)一個GetEnumerator函數(shù),該函數(shù)返回的是一個類型為IEnumerator 的對象,,于是我們再寫一個類繼承自IEnumerator 接口:
01.public class PersonEnumerator : IEnumerator
02. {
03. //定義一個字符串數(shù)組
04. private string[] _names;
05.
06. //遍歷時的索引
07. private int index = -1;
08.
09. //構造函數(shù),,帶一個字符串數(shù)組的參數(shù)
10. public PersonEnumerator(string[] temp)
11. {
12. _names = temp;
13. }
14.
15. //返回當前索引指向的names數(shù)組中的元素
16. public object Current
17. {
18. get { return _names[index]; }
19. }
20.
21. //索引,,判斷是否遍歷完成
22. public bool MoveNext()
23. {
24. index++;
25. if (index < _names.Length)
26. {
27. return true;
28. }
29. else
30. return false;
31. }
32.
33. //重置索引的值,以便下一次遍歷
34. public void Reset()
35. {
36. index = -1;
37. }
38. }
然后對GetEnumerator函數(shù)稍加修改就大功告成了,,如下:
01.public class Person : IEnumerable
02. {
03. private string[] names = new string[] { "A", "B", "C" };
04.
05. public IEnumerator GetEnumerator()
06. {
07. //調用PersonEnumerator類的構造函數(shù),,并Person類中的names數(shù)組傳遞過去
08. return new PersonEnumerator(names);
09. }
10. }
然后就可以用foreach對Person類的對象進行遍歷了,如下:
01.static void Main(string[] args)
02. {
03. Person p1 = new Person();
04. foreach (string item in p1)
05. {
06. Console.WriteLine(item);
07. }
08. Console.ReadKey();
09. }
我們也可以用如下方法對names數(shù)組進行遍歷:
01.static void Main(string[] args)
02. {
03. Person p1 = new Person();
04. IEnumerator rator = p1.GetEnumerator();
05. while (rator.MoveNext())
06. {
07. Console.WriteLine(rator.Current);
08. }
09. Console.ReadKey();
10. }
|