<分区> 分区>
所以我有一个通用类 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
}
基本上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'.
我不知道是什么问题。
