这是一个很经典的例子,推荐大家可以分析一下
public class LinkedListNode<T>
{
public LinkedListNode(T value)
{
Value = value;
}
public T Value {get; private set;}
public LinkedListNode<T> Next {get; internal set;}
public LinkedListNode<T> Prev {get; internal set;}
}
public class LinkedList<T>: IEnumberable<T>
{
public LinkedListNode<T> First {get; private set;}
public LinkedListNode<T> Last {get; private set;}
public LinkedListNode<T> AddLast(T node)
{
var newNode = new LinkedListNode<T>(node);
if(First == null)
{
First = newNode;
Last = First;
}
else
{
// 这段代码试着理解它吧
LinkedListNode<T> previous = Last;
Last.Next = newNode;
Last = newNode;
Last.Prev = pervious;
}
return newNode;
}
public IEnumerator<T> GetEnumerator()
{
LinkedListNode<T> current = First;
while(current != null)
{
yield return current.Value;
current = current.Next;
}
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumberator();
}
var list1 = new LinkedList<int>();
list1.AddLast(1);
list1.AddLast(3);
list1.AddLast(5);
foreach(int i in list1)
{
Console.WriteLine(i);
}
var list2 = new LinkedList<string>();
list2.AddLast("hello");
list2.AddLast("world");
foreach(string i in list2)
{
Console.WriteLine(i);
}
注意: 每个处理对象类型的类都可以有泛型实现方式, 如果类使用了层次结构,泛型就非常有助于消除类型强制转换操作。