码迷,mamicode.com
首页 > 其他好文 > 详细

创建一个简单的迭代器

时间:2016-09-22 23:39:20      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

在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 Count
15         {
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 Current
13         {
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 关键字告诉编译器去执行实现过程,我们程序员就减少了编码量

 

 

 

 

创建一个简单的迭代器

标签:

原文地址:http://www.cnblogs.com/sddz/p/5898254.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!