Can anyone explain IEnumerable and IEnumerator to

2019-01-01 14:05发布

Can anyone explain IEnumerable and IEnumerator to me?

for example, when to use it over foreach? what's the difference between IEnumerable and IEnumerator? Why do we need to use it?

14条回答
妖精总统
2楼-- · 2019-01-01 14:48

An understanding of the Iterator pattern will be helpful for you. I recommend reading the same.

Iterator Pattern

At a high level the iterator pattern can be used to provide a standard way of iterating through collections of any type. We have 3 participants in the iterator pattern, the actual collection (client), the aggregator and the iterator. The aggregate is an interface/abstract class that has a method that returns an iterator. Iterator is an interface/abstract class that has methods allowing us to iterate through a collection.

In order to implement the pattern we first need to implement an iterator to produce a concrete that can iterate over the concerned collection (client) Then the collection (client) implements the aggregator to return an instance of the above iterator.

Here is the UML diagram Iterator Pattern

So basically in c#, IEnumerable is the abstract aggregate and IEnumerator is the abstract Iterator. IEnumerable has a single method GetEnumerator that is responsible for creating an instance of IEnumerator of the desired type. Collections like Lists implement the IEnumerable.

Example. Lets suppose that we have a method getPermutations(inputString) that returns all the permutations of a string and that the method returns an instance of IEnumerable<string>

In order to count the number of permutations we could do something like the below.

 int count = 0;
        var permutations = perm.getPermutations(inputString);
        foreach (string permutation in permutations)
        {
            count++;
        }

The c# compiler more or less converts the above to

using (var permutationIterator = perm.getPermutations(input).GetEnumerator())
        {
            while (permutationIterator.MoveNext())
            {
                count++;
            }
        }

If you have any questions please don't hesitate to ask.

查看更多
柔情千种
3楼-- · 2019-01-01 14:51
  • An object implementing IEnumerable allows others to visit each of its items (by an enumerator).
  • An object implementing IEnumerator is the doing the iteration. It's looping over an enumerable object.

Think of enumerable objects as of lists, stacks, trees.

查看更多
登录 后发表回答