c# - 为什么接口 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 的方法?
解决方案
您可以在这篇非常好的文章中检查差异
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);
}
}
推荐阅读
- android-studio - 没有为 com.android.support:appcompat-v7:26.0.0-alpha1 的属性“appComponentFactory”找到资源标识符
- c++ - 使用boost asio时如何实现限制上传文件大小
- c# - 一旦我抓住同一个物体,如何扔掉一个物体
- machine-learning - GridSearchCV + StratifiedKfold 在 TFIDF 的情况下
- mysql - MYSQL 8.0.19 (ON PREMISE) 作为 AWS DMS 中的源?
- java - 解密使用openssl、oaep填充模式加密的非对称密钥
- flutter - Flutter 应用程序丢失 java.lang.UnsatisfiedLinkError (couldn't find "libflutter.so") Flutter (Channel unknown, v1.12.13+hotfix.9)
- c# - Debugger Visualizer Winform ToolStripDropDownMenu ComboBox 仅在首次显示时显示项目
- powershell - Powershell错误的退出点
- javascript - Javascipt 在三星互联网浏览器中不起作用