Implementing C# IEnumerable<T> for a LinkedList class

怎甘沉沦 提交于 2019-12-01 09:17:34

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();
}

When i tried the code that you have pasted i get 2 errors when trying to build.

myLinkedList' does not implement interface member 'System.Collections.IEnumerable.GetEnumerator()'. '.myLinkedList.GetEnumerator()' cannot implement 'System.Collections.IEnumerable.GetEnumerator()' because it does not have the matching return type of 'System.Collections.IEnumerator'.

Solution is to implement the following in the first class.

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

And the second error is :

myLinkedList.myLinkedListIterator' does not implement interface member 'System.Collections.IEnumerator.Current'. 'JonasApplication.myLinkedList.myLinkedListIterator.Current' cannot implement 'System.Collections.IEnumerator.Current' because it does not have the matching return type of 'object'.

Solution to the second could be something as following to implement in the second class.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!