1.3.50 #
解答 #
初始化迭代器的时候记录栈已经进行过的 Pop 和 Push 数,迭代的时候检查这两个值是否改变,一旦改变就抛出异常。
代码 #
private class StackEnumerator : IEnumerator<Item>
{
private Stack<Item> s;
private int popcount;
private int pushcount;
private Node<Item> current;
public StackEnumerator(Stack<Item> s)
{
this.s = s;
this.current = s.first;
this.popcount = s.popcount;
this.pushcount = s.pushcount;
}
Item IEnumerator<Item>.Current => current.item;
object IEnumerator.Current => current.item;
void IDisposable.Dispose()
{
this.current = null;
this.s = null;
}
bool IEnumerator.MoveNext()
{
if (s.popcount != this.popcount || s.pushcount != this.pushcount)
throw new InvalidOperationException("Stack has been modified");
if (this.current.next == null)
return false;
this.current = this.current.next;
return true;
}
void IEnumerator.Reset()
{
this.current = this.s.first;
}
}