Foreach首先在枚举器中调用MoveNext,当前第二个

问题描述 投票:0回答:1

我的问题基本上是按照所调用的功能/属性的顺序。我有一个自定义的链接列表,一个。所以我做了一个自定义的枚举器。问题是,foreach循环实际上首先调用枚举器的MoveNext()方法,因此从循环的实际第一个Node移到第二个节点,如果您希望按实际顺序放置项目,这是很糟糕的。

问题是,我做错什么了,如果没有,如何弥补?

枚举器的代码很简单。基本上,这是:

class EnumeratorLinkedList : IEnumerator<Node>
    {
        //
        private Node current;
        private Node first;
        private bool didWeMove;

        public EnumeratorSpojovySeznam(Node current)
        {
            this.current = current;
            this.first = current;
            didWeMove = false;
        }

        public Node Current => current;

        object System.Collections.IEnumerator.Current => Current;

        public bool MoveNext()
        {

            if ((didWeMove == true && current == first)) return false;
            current = current.Next;
            didWeMove = true;
            return true;
        }

        public void Dispose()
        {

        }

        public void Reset()
        {
            throw new NotImplementedException();
        }
    }
c# foreach enumerator
1个回答
0
投票

您是否考虑使用C# iterators为您的通告C# iterators实现枚举器?如果这样做,这非常简单。 LinkedList提供了实现枚举器的便捷方法。

这里是如何为您的通告Iterators实现枚举器:

LinkedList

这里是class LinkedList : IEnumerable<Node> { private Node first; public IEnumerator<Node> GetEnumerator() { // Check if LinkedList is empty. // If it is empty we immediately break enumeration. if (first == null) yield break; // Here goes logic for enumerating circular LinkedList. Node current = first; do { yield return current; current = current.Next; } while (current != first); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } ,演示了complete sample的用法。

© www.soinside.com 2019 - 2024. All rights reserved.