所以我有一个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>
s 的集合。这只是对我自己建立一个像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'.
我不知道是什么问题。