何时调用IEnumerator.Reset()方法? [英] When IEnumerator.Reset() method is called?

查看:210
本文介绍了何时调用IEnumerator.Reset()方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们有这个代码:

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

    #region IEnumerator Members

    public object Current
    {
        get { return A[i]; }
    }

    public bool MoveNext()
    {
        i++;
        return i < 5;
    }

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

    #endregion

    #region IEnumerable Members

    public IEnumerator GetEnumerator()
    {
        return (IEnumerator)this;
    }

    #endregion
}

在主方法中:

MyList list = new MyList();
foreach (int i in list)
{
    Console.WriteLine(i);
}

foreach (int i in list)
{
    Console.WriteLine(i);
}

为什么第二个foerach不起作用?并且i不会再次初始化?

Why the second foerach doesn't work ?? and the "i" doesn't initialize again ??

这是真的:在执行foreach之前应该自动调用Reset方法吗?

Is that true : Reset method should be called automatically before foreach is executed ??

为什么不在这里打电话?

why it doesn't call here ??

推荐答案

IEnumerable和IEnumerator通常应该是单独的类,除了总是返回空的枚举数或总是返回同一项,GetEnumerator方法必须始终返回IEnumerator的新实例。

The IEnumerable and IEnumerator should generally be separate classes, and except in the case of enumerators that always return empty or always return the same item, the GetEnumerator method must always return a new instance of an IEnumerator.

IEnumerator.Reset没有多大意义; for-each循环不使用它,并且IEnumerable / IEnumerator的使用者不能使用它,除非他们知道可枚举类型是什么,在这种情况下他们可以使用实际类型而不是接口。

There isn't much point to IEnumerator.Reset; for-each loops don't use it, and consumers of an IEnumerable/IEnumerator can't use it unless they know what the enumerable type is, in which case they could use the actual type rather than the interface.

这篇关于何时调用IEnumerator.Reset()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆