Mutability of the Enumerator structure

I have a problem with the following code:

  public static void RestoreToolStripMenuItem(ToolStripMenuItem item, List<string>.Enumerator enumerator )
    {
        item.Text = enumerator.Current;
        enumerator.MoveNext();

        if (item.HasDropDownItems)
        {
            var itemsWithoutSeparators = item.DropDownItems.OfType<ToolStripMenuItem>();
            foreach (var child in itemsWithoutSeparators)
            {
                RestoreToolStripMenuItem(child, enumerator);
            }
        }

}

After RestoreToolStripMenuItem is called recursively, the counter is reset (the current property points to the first element of the collection). It can be processed by clicking the enumerator link. I wonder why this is so? An enumerator is a structure. What caused this problem, the variability of the structure of the Enumerator?

+3
source share
3 answers

Yes, this is the changing state of the structure that causes it.

If you pass a structure by value, you will use a copy of it in the method, and the code in the calling code will not change.

+2
source

, IEnumerator (Of String) . , , .

+1

Just revert the modified Enumerator structure from the method you are calling and assign it back to the original variable.

0
source

Source: https://habr.com/ru/post/1795696/


All Articles