【发布时间】:2012-07-13 14:09:41
【问题描述】:
我基本上是想让我的班级能够使用foreach 进行迭代。我读了这个教程。 MSDN。这似乎很简单。但是,当我想第二次迭代时遇到问题。我调试了它;结果它没有调用Reset()函数。
A 类
class A : IEnumerable, IEnumerator
{
int[] data = { 0, 1, 2, 3, 4 };
int position = -1;
public object Current
{
get
{
return data[position];
}
}
public bool MoveNext()
{
position++;
return (position < data.Length);
}
public void Reset()
{
position = -1;
}
public IEnumerator GetEnumerator()
{
return (IEnumerator)this;
}
}
当我运行以下主要功能时;它从不调用Reset() 函数。所以,在一个循环之后,我再也无法迭代我的类了。
主要
static void Main(string[] args)
{
A a = new A();
foreach (var item in a)
{
Console.WriteLine(item);
}
Console.WriteLine("--- First foreach finished. ---");
foreach (var item in a)
{
Console.WriteLine(item);
}
}
输出:
0
1
2
3
4
--- First foreach finished. ---
Press any key to continue . . .
有什么想法吗?
【问题讨论】:
-
看看这个answer
-
顺便说一句,除非你是为了好玩或一个非常具体的原因,否则你永远不必以这种方式实现迭代器。查看“迭代器块”又名“收益回报”。
-
我知道它很旧,但我刚刚在谷歌上找到了这篇文章。我遇到了同样的问题,我实现了 MoveNext 方法,当它返回 false 时调用 Reset。
标签: c# foreach enumerable enumerator