简体   繁体   English

为什么接口 IEnumerable 返回 IEnumerator GetEnumemrator()? 为什么不只实现接口 IEnumerator?

[英]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?为什么不直接实现 IEnumerator 而不是使用 IEnumerable 强制您实现一个返回类型 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. TL;DR - 实际上, IEnumerable合同假定您有一种方法可以维护 Enumerable 的状态。

Similarities相似之处

Both of these interfaces help to loop through the collection.这两个接口都有助于循环遍历集合。

Relation关系

The IEnumerable interface actually uses IEnumerator. IEnumerable 接口实际上使用了 IEnumerator。 The main reason to create an IEnumerable is to make the syntax shorter and simpler.创建 IEnumerable 的主要原因是使语法更短更简单。

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.如果转到 IEnumerable 接口的定义,您将看到该接口有一个方法 GetEnumerator(),该方法返回一个 IEnumerator 对象。

Differences差异

The main difference between IEnumerable and IEnumerator is an IEnumerator retains its cursor's current state. IEnumerable 和 IEnumerator 之间的主要区别在于 IEnumerator 保留其光标的当前状态。

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.因此,如果您想按顺序循环遍历集合,请使用 IEnumerable 接口,否则如果您想保留光标位置并希望将其从一个函数传递到另一个函数,则使用 IEnumerator 接口。

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);  
     }  
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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