Ady*_*emp 60
无论何时您想要移动列表中的"下一个"部分,都可以快速解决以循环方式使用它的方法:
current = current.Next ?? current.List.First;
Run Code Online (Sandbox Code Playgroud)
目前的情况LinkedListNode<T>
.
虽然 LinkedList 的公共 API 不是循环的,但实际上它在内部是循环的。查阅参考源,你可以看到它是如何实现的:
// This LinkedList is a doubly-Linked circular list.
internal LinkedListNode<T> head;
Run Code Online (Sandbox Code Playgroud)
当然,为了隐藏它是循环的事实,遍历列表的属性和方法进行检查以防止返回到头部。
链表节点:
public LinkedListNode<T> Next {
get { return next == null || next == list.head? null: next;}
}
public LinkedListNode<T> Previous {
get { return prev == null || this == list.head? null: prev;}
}
Run Code Online (Sandbox Code Playgroud)
LinkedList.Enumerator:
public bool MoveNext() {
if (version != list.version) {
throw new InvalidOperationException(SR.GetString(SR.InvalidOperation_EnumFailedVersion));
}
if (node == null) {
index = list.Count + 1;
return false;
}
++index;
current = node.item;
node = node.next;
if (node == list.head) {
node = null;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)