繁体   English   中英

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

[英]Why does interface IEnumerable return IEnumerator GetEnumemrator()? Why not just implement interface 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 的方法?

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

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

暂无
暂无

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

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