我有一个像这样的代码:
class T : IEnumerable, IEnumerator
{
private int position = -1;
public T() { }
public IEnumerator GetEnumerator() { return this; }
public object Current { get { return position; } }
public bool MoveNext()
{
position++;
return (position < 5);
}
public void Reset() { position = -1; }
}
//Using in code:
T t = new T();
foreach (int i in t)
//to do something
在上面的代码中一切正常,但是当我使用下一个时:
foreach (int i in t)
if (i == 2)
foreach (int p in t)
//print p
else
//print i
它打印(在括号中的第二个循环中): 0 1 (3 4) 2 而不是 0 1 (0 1 2 3 4) 2 3 4 我在 List 和 Collection 上测试了它,他们做得对。我怎样才能达到我所需要的?