C#用yield实现简单的迭代器

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Collections;
 6 
 7 namespace IEnumrableTest
 8 {
 9     class YeildIEnumerable:IEnumerable<Person>
10     {
11         private List<Person> list = new List<Person>();
14         public YeildIEnumerable()
15         {
17             list.Add(new Person { Name = "Harley"});
18             list.Add(new Person { Name = "Hu"});
19         }
20 
21         public IEnumerator<Person> GetEnumerator()
22         {
23             for (int i = 0; i < list.Count; i++)
24             {
25                 yield return list[i];
26             }                     
27         }
28 
29         IEnumerator IEnumerable.GetEnumerator()
30         {
31             return null;
32         }
33     }
34 }

 

posted @ 2012-12-03 17:17  Harley Hu  阅读(230)  评论(0编辑  收藏  举报