I read about IEnumerable:

IEnumerable or IEnumerable<T> : by implementing this an object states that it can give you an iterator that you can use to traverse over the sequence/collection/set

So, the foreach statement uses only the IEnumerable interface to iterate over a collection ?

Or does it use IEnumerator too ?

有帮助吗?

解决方案

IEnumerable exposes a single method, which returns an IEnumerator. So, the answer is: it uses both.

其他提示

IEnumerator does not expose GetEnumerator so a foreach will throw an error.

IEnumerable numbers = new[]{1,2,3,4,5};
foreach(var number in numbers) //finds GetEnumerator()
{
    Console.WriteLine(number);
}

IEnumerator numbers2 = new[]{1,2,3,4,5}.GetEnumerator();
foreach(var number in numbers2) //cannot find GetEnumerator, throws
{
    Console.WriteLine(number);
}

The second foreach will throw an error because foreach is specifically looking for the GetEnumerator method which is not exposed on IEnumerator its self.

If you look at the IEnumerable interface, you will find out that its only method is to get IEnumerator to iterate.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top