IEnumerator与IEnumerable探讨

一套完整的 IEnumerator 和IEnumerable 关系

    public class MyClass : IEnumerator
{
public MyClass(int Size)
{
this.Index = -1;
Info = new string[Size];
for (int i = 0; i < Size; i++)
{
Info[i] = i.ToString();
}
}

private string[] Info;
public int Index;
public object Current { get { return Info[Index]; } }

public bool MoveNext()
{
Index++;
return Index >= Info.Length ? false : true;
}

public void Reset()
{
Index = -1;
}

}
public class MyClassCollection : IEnumerable
{
private MyClass ml = null;
public MyClassCollection(int Size)
{
ml = new MyClass(Size);
}
public IEnumerator GetEnumerator()
{
return (IEnumerator)ml;
}
}

调用:

 MyClassCollection cl = new MyClassCollection(10);
            foreach (var item in cl)
            {
                Console.WriteLine(item);
            }

结果:0到9

个人理解:1.IEnumerable 只是用来被 循环调用。不能自己实现foreach,需要用GetEnumerator 将自己的成员。传给IEnumerator,进行循环。

也就是 在foreach中 item 其实是 IEnumerator 中的返回的结果。

2.必须知道的事  IEnumerable 必须实现  接口中 GetEnumerator方法。

IEnumerator 实现  Current。MoveNext。Reset (不然会空引用)

3.可以将IEnumerator和 IEnumerable 结合到一块。

4. 可以不继承IEnumerable,但一定要实现 GetEnumerator方法。~!!!!!

待续。。

原文地址:https://www.cnblogs.com/shikyoh/p/2246456.html