且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

实现 C# IEnumerable<T>对于 LinkedList 类

更新时间:2022-10-24 20:20:00

You need to add the non-generic APIs; so add to the iterator:

object System.Collections.IEnumerator.Current { get { return Current;  } }

and to the enumerable:

System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
    return GetEnumerator();
}

HOWEVER! If you are implementing this by hand, you are missing a trick. An "iterator block" would be much easier.

The following is a complete implementation; you don't need to write an enumerator class at all (you can remove myLinkedListIterator<T> completely):

public IEnumerator<T> GetEnumerator()
{
    var node = front;
    while(node != null)
    {
        yield return node.data;
        node = node.next;
    }
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
    return GetEnumerator();
}