使用 foreach 遍历自定义类型中的数据(简单例子)

这个例子适用于 .net Framework 2.0 以上版本。

一个简单的类
 1     internal class GoodsShelf
 2     {
 3         // 货物列表
 4         string[] goods = { "First thing""Second thing""Third thing""Fourth thing""Fifth thing" };
 5 
 6         /// <summary>
 7         /// 获取迭代器
 8         /// </summary>
 9         /// <returns></returns>
10         public IEnumerator GetEnumerator()
11         {
12             for (int i = 0; i < goods.Length; i++)
13             {
14                 yield return goods[i];
15             }
16         }
17 
18     }

 

使用 foreach 循环 需要给它提供一个支持迭代的类型。即提供一个 IEnumerator 或者 IEnumerable 接口的实现,上例中自定义的类型并没有实现这两个接口之中的任意一个,但是我们可以主动的给他一个返回 IEnumerator 或者 IEnumerable 的 GetEnumerator() 方法。

这个 GetEnumerator() 方法的返回方式为 yield returnyield 关键字在迭代器块中用于向枚举数对象提供值或发出迭代结束信号。关于 yield 关键字详见。

 测试例子

 1     class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             GoodsShelf goods = new GoodsShelf();
 6             foreach (var item in goods)
 7             {
 8                 Console.WriteLine(item);
 9             }
10         }
11 
12     }

 

输出结果First thing
Second thing
Third thing
Fourth thing
Fifth thing

 


posted @ 2010-05-12 20:51  東 無盡  阅读(537)  评论(0编辑  收藏  举报