首页 > 解决方案 > 为什么接口 IEnumerable 返回 IEnumerator GetEnumemrator()?为什么不直接实现接口 IEnumerator?

问题描述

例如:

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

为什么不直接实现 IEnumerator 而不是使用 IEnumerable 来强制您实现返回类型 IEnumerator 的方法?

标签: c#interface

解决方案


您可以在这篇非常好的文章中检查差异

TL;DR - 实际上,IEnumerable合同假定您有办法维护 Enumerable 的状态。

相似之处

这两个接口都有助于遍历集合。

关系

IEnumerable 接口实际上使用了 IEnumerator。创建 IEnumerable 的主要原因是使语法更短更简单。

如果您转到 IEnumerable 接口的定义,您将看到该接口有一个 GetEnumerator() 方法,该方法返回一个 IEnumerator 对象。

差异

IEnumerable 和 IEnumerator 之间的主要区别是 IEnumerator 保留其光标的当前状态。

何时使用:

因此,如果要按顺序循环遍历集合,请使用 IEnumerable 接口,否则如果要保留光标位置并将其从一个函数传递到另一个函数,则使用 IEnumerator 接口。

例子:

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

推荐阅读