When IEnumerator.Reset() method is called?

后端 未结 6 562
醉话见心
醉话见心 2021-01-11 14:51

let\'s have this code :

class MyList : IEnumerable, IEnumerator
{
    int[] A = { 1, 2, 3, 4, 5 };
    int i = -1;

    #region IEnumerator Members

    pub         


        
6条回答
  •  隐瞒了意图╮
    2021-01-11 15:29

    Reset is not called by foreach. Looking at your Main method in Reflector confirms this.

    The .NET classes, like ArrayList, actually return a new instance of a class that implements IEnumerator.

    For example ArrayList implements IEnumerable, and its GetEnumerator method looks like this:

    public virtual IEnumerator GetEnumerator()
    {
        return new ArrayListEnumeratorSimple(this);
    }
    

    so there is no need to worry about calling Reset since every foreach uses a new instance of the enumerator.

    For a complete example showing the implementation of IEnumerable and a separate class implementing IEnumerator, you can look at the documentation for IEnumerable.

提交回复
热议问题