简体   繁体   中英

Why does interface IEnumerable return IEnumerator GetEnumemrator()? Why not just implement interface IEnumerator?

For example:

public interface IEnumerable
{
     IEnumerator GetEnumerator();
}

//This interface allows the caller to obtain a container's items.
public interface IEnumerator
{
bool MoveNext ();
object Current { get;}
void Reset();
}

Why not just implement IEnumerator instead of using IEnumerable that forces you to implement a method that returns type IEnumerator?

You can check the differences at this very nice article

TL;DR - Effectively, the IEnumerable contract assumes that you have a way of maintaning the state of the Enumerable.

Similarities

Both of these interfaces help to loop through the collection.

Relation

The IEnumerable interface actually uses IEnumerator. The main reason to create an IEnumerable is to make the syntax shorter and simpler.

If you go to the definition of the IEnumerable interface, you will see this interface has a method GetEnumerator() that returns an IEnumerator object back.

Differences

The main difference between IEnumerable and IEnumerator is an IEnumerator retains its cursor's current state.

When to use:

So, if you want to loop sequentially through the collection, use an IEnumerable interface else if you want to retain the cursor position and want to pass it from one function to another function then use an IEnumerator interface.

Example:

static void iEnumeratorMethodOne(IEnumerator<string> i)  
{  
   while(i.MoveNext())  
   {  
      Console.WriteLine(i.Current);  
  
       if(i.Current == "June")  
       {  
          iEnumeratorMethodTwo(i);  
       }  
    }  
}  
  
static void iEnumeratorMethodTwo(IEnumerator<string> i)  
{  
    while(i.MoveNext())  
    {  
       Console.WriteLine(i.Current);  
     }  
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM