Вопрос

I want to know because I am planning on using an enumerator for a linked list and want to be able to remove a node if its data is changed to a certain value during the programs running. But since an enumerator would have its MoveNext() get the next node in the list I want to know if the MoveNext() is called after the Current's get.

In otherwords, will this work without the linked list enumerator stopping right after the remove.

foreach (Node<Object> it in myLinkedList)
{
    if (it.data().isGone())
    {
        myLinkedList.remove(it);
    }
}

public boolean remove(Node<E> node)
{
    node.setData(node.next().data());
    node.setNext(node.next().next());
}
Это было полезно?

Решение

According to the documentation for IEnumerator<T>, the MoveNext() method will throw an InvalidOperationException if the collection is modified after the enumerator was created.

IEnumerator<T>.MoveNext()

Even if you implement your own enumerator that does not behave this way (including a select few included in .NET), you should never modify a collection inside of a foreach statement which is enumerating the elements of that collection, since that is an immediate visual indication that your code is likely to throw an exception.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top