您的位置:首页 > 编程语言 > C#

C# 通过实现IEnumerable/IEnumerator接口 完成foreach遍历

2012-02-25 00:00 330 查看
将IEnumerable看做一个类工厂,IEnumerator是一个迭代器对象,通过类工厂生产一个迭代器返回该迭代器对象接口,由foreach执行迭代器完成遍历查询。如果熟悉设计模式中的类工厂模式,是很容易理解c#中这个概念的~

MyEnumerable 类:

using System;

using System.Collections;

using System.Linq;

using System.Text;

namespace EnumerableTest

{

public class MyEnumerable : IEnumerable, IEnumerator

{

private int iIndex;

private CellInfo[] points;

public MyEnumerable(int num)

{

this.iIndex = -1;

points = new CellInfo[num];

for (int i = 0; i < num; i++)

{

points[i] = new CellInfo() { Name = ("my name" + i), Age = i };

}

}

public IEnumerator GetEnumerator()//
可以看做一个工厂 生产一个迭代器

{

return (IEnumerator)this;

}

int index = -1;

public void Reset()

{

index = -1;

}

public object Current

{

get

{

return points[index];

}

}

public bool MoveNext()

{

index++;

return index < points.Length ? true : false;

}

}

}

program类:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace EnumerableTest

{

class Program

{

static void Main(string[] args)

{

MyEnumerable enumerable = new MyEnumerable(10);

foreach (CellInfo item in enumerable)

{

Console.WriteLine(item.Name+" "+item.Age);

}

Console.Read();

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐