gpt4 book ai didi

c# - 为什么接口(interface) IEnumerable 返回 IEnumerator GetEnumemrator()?为什么不直接实现接口(interface) IEnumerator?

转载 作者:行者123 更新时间:2023-12-01 03:02:14 26 4
gpt4 key购买 nike

例如:

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 的方法?

最佳答案

您可以在 this very nice article 上查看差异。
TL;DR - 实际上,IEnumerable合约假设你有办法维护 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.


何时使用:

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.


例子:
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);
}
}

关于c# - 为什么接口(interface) IEnumerable 返回 IEnumerator GetEnumemrator()?为什么不直接实现接口(interface) IEnumerator?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60349803/

26 4 0