这个例子适用于 .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 }
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 }