自定义集合无法实现IEnumerable <t> </t>

时间:2013-08-21 11:07:03

标签: c# linked-list ienumerable

所以我有一个通用类Node<T>,看起来像这样。它只保留值和下一个Node<T>

的引用
public class Node<T>
{
    public T Value { get; set; }
    public Node<T> Next { get; set; }

    // Some Methods go here
}

还有另一个名为CustomLinkedList<T>的类,看起来像这样

public class CustomLinkedList<T> : IEnumerable<T>
{
    Node<T> m_first;
    Node<T> m_current;
    int m_length;

    public CustomLinkedList()
    {
        m_first = new Node<T>();
        m_current = m_first;
        m_length = 0;
    }

    // Adding, removing and other methods go here
}

Baisically CustomLinkedList<T>Node<T>的集合。这对我自己构建像LinkedList<T>这样的集合来说是一个挑战(至少我认为是这样)。下面的代码显示了我如何实现添加功能的示例。

public void AddLast(T value)
{
    m_current.Value = value;
    m_current.Next = new Node<T>();
    m_current = m_current.Next;
    m_length++;
}

public void AddFirst(T value)
{
    Node<T> newFirst = new Node<T>();
    newFirst.Value = value;
    newFirst.Next = m_first;
    m_first = newFirst;
    m_length++;
}

还有AddAfter()AddBefore()方法以及一些RemoveXXX()方法。所以我希望CustomLinkedList<T>实现IEnumerable<T>,我的GetEnumerator()方法看起来像这样

public IEnumerator<T> GetEnumerator()
{
    if (m_length > 0)
    {
        Node<T> nodeToReturn = m_first;
        for (int i = 0; i < m_length; i++)
        {
            if (nodeToReturn == null)
                break;
            yield return nodeToReturn.Value;
            nodeToReturn = nodeToReturn.Next;
        }
    }
}

但编译器抱怨关注

CustomGenericCollections.CustomLinkedList<T>' does not implement interface member 'System.Collections.IEnumerable.GetEnumerator()'. 'CustomGenericCollections.CustomLinkedList<T>.GetEnumerator()' cannot implement 'System.Collections.IEnumerable.GetEnumerator()' because it does not have the matching return type of 'System.Collections.IEnumerator'.

我无法弄清问题是什么。

1 个答案:

答案 0 :(得分:4)

由于IEnumerable<T>继承自IEnumerable,因此您还需要实现非通用GetEnumerator()。将此添加到您的班级:

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