首页 > 代码库 > 创建一个简单的迭代器

创建一个简单的迭代器

在C# 1.0中,自己写代码实现IEnumerator

 1   class IterateCollection : IEnumerable 2     { 3         private string[] strarr = new string[5]; 4         public IterateCollection() { } 5         public IterateCollection(string[] strarr) 6         { 7             this.strarr = strarr; 8         } 9         public string this[int index]10         {11             get { return strarr[index]; }12         }13 14         public int Count15         {16             get { return strarr.Length; }17         }18 19         public IEnumerator GetEnumerator()20         {21             return new IterateEnumertor(this);22         }23        24     }

 1 class IterateEnumertor : IEnumerator 2     { 3         private readonly IterateCollection collection; 4         private int index; 5         private object current; 6         public IterateEnumertor(IterateCollection collection)  7         { 8             this.collection = collection; 9             index = 0;10         }11 12         public object Current13         {14 15             get { return current; }16         }17 18         public bool MoveNext()19         {20             if (index + 1 > collection.Count) { return false; }21             else 22             {23                 this.current = collection[index];24                 index++;25                 return true;26             }27         }28 29         public void Reset()30         {31             index = 0;    32         }33     }

 1   static void Main(string[] args) 2         { 3             string[] strarr = { "刘诗诗","陈乔恩","刘亦菲"}; 4             IterateCollection collection = new IterateCollection(strarr); 5             foreach(string str in collection) 6             { 7                 Console.WriteLine(str.ToString()); 8             } 9             Console.Read();10         }

 

摘要:1 想要可以被迭代,就要实现IEnumerable,或者IEnumerable<T>,并且重写GetEnumerator();方法,得到一个迭代器

     2 在C#1.0中迭代器要自己写,通过实现IEnumerator,或者IEnumerator<T>,并且重写MoveNext();和Reset();方法

 

C#2.0简化了迭代器的实现

   

1        public IEnumerator GetEnumerator()2         {3             //return new IterateEnumertor(this);4             for (int index = 0; index < strarr.Length; index++) 5             {6                 yield return strarr[index];7             }8         }
摘要 yield return 关键字告诉编译器去执行实现过程,我们程序员就减少了编码量

 

 

 

 

创建一个简单的迭代器