IEnumerable的&放大器; IEnumerator的

IEnumerable的&放大器; IEnumerator的

问题描述:

任何人能请向我解释什么是IEnumerable的与放大器之间的差异; IEnumerator的, 以及如何使用它们?

Can anyone please explain to me what is the difference between IEnumerable & IEnumerator , and how to use them?

谢谢!

通常,的IEnumerable 是一个可以列举,如列表或数组对象。一个的IEnumerator 是一个对象存储枚举的状态。

Generally, an IEnumerable is an object which can be enumerated, such as a list or array. An IEnumerator is an object that stores the state of the enumeration.

他们不是一个和相同的原因是,你可以有多个枚举了在同一时间对同一对象 - 即使是在一个单线程应用程序。例如,请考虑以下code:

The reason they're not one and the same is that you could have multiple enumerations over the same object at the same time - even in a single-threaded application. For example, consider the following code:

foreach (x in mylist)
{
    foreach (y in mylist)
    {
        if (x.Value == y.Value && x != y)
        {
            // Found a duplicate value
        }
    }
}

这将正常工作,如果 mylist中是一个正确执行的IEnumerable 的,但它会失败,如果 mylist中返回自己作为枚举。

This would work fine if mylist is a proper implementation of IEnumerable, but it would fail if mylist returned itself as the enumerator.