我在这里制作一个单独的线程,因为我相信如果我写了一个评论,评论不会把线程推到顶部,因此会有任何人谁写的线程通知。
此代码由micheal buen在线程Writing text to the middle of a file处提供:
LinkedList<string> beatles = new LinkedList<string>();
beatles.AddFirst("John");
LinkedListNode<string> nextBeatles = beatles.AddAfter(beatles.First, "Paul");
nextBeatles = beatles.AddAfter(nextBeatles, "George");
nextBeatles = beatles.AddAfter(nextBeatles, "Ringo");
nextBeatles = beatles.AddAfter(nextBeatles, "George");
nextBeatles = beatles.AddAfter(nextBeatles, "Ringo");
nextBeatles = beatles.AddAfter(nextBeatles, "George");
nextBeatles = beatles.AddAfter(nextBeatles, "Ringo");
nextBeatles = beatles.AddAfter(nextBeatles, "George");
nextBeatles = beatles.AddAfter(nextBeatles, "Ringo");
nextBeatles = beatles.AddAfter(nextBeatles, "George");
nextBeatles = beatles.AddAfter(nextBeatles, "Ringo");
// change the 1 to your 5th line
LinkedListNode<string> paulsNode = beatles.NodeAt(6);
LinkedListNode<string> recentHindrance = beatles.AddBefore(paulsNode, "Yoko");
recentHindrance = beatles.AddBefore(recentHindrance, "Aunt Mimi");
beatles.AddBefore(recentHindrance, "Father Jim");
Console.WriteLine("{0}", string.Join("\n", beatles.ToArray()));
Console.ReadLine();
public static class Helper
{
public static LinkedListNode<T> NodeAt<T>(this LinkedList<T> l, int index)
{
LinkedListNode<T> x = l.First;
while ((index--) > 0)
{
x = x.Next;
Console.Write(x.Value);
Thread.Sleep(10000);
}
return x;
}
}
我想知道的是,扩展方法实现了什么?
在第一次传球时,x=x。下一次是指我们看的是林戈而不是乔治,以此类推从我调用nodeat(6)开始,引擎盖下面到底发生了什么,代码在做什么?我之所以这么问,是因为能够阅读和理解代码而无需使用单步执行方法作为辅助(例如,有时在工作中,您将阅读打印文档中的代码)是很重要的另外,为什么我们要在循环中倒数,为什么在进入循环体之前有一个括号要减去1?
谢谢
最佳答案
扩展方法只遍历LinkedListn
元素,它用列表的第一个元素初始化x
(l.first),然后在这段时间内,它将索引递减为step forwardn
次(lookx = x.Next;
):
Index: 1 2 3 4 _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ | John |-> | Paul |-> | George |-> | Ringo | ‾ ‾ ‾ ‾ ‾ ‾ ‾ ‾ ‾ ‾ ‾ ‾ ‾ ‾ ‾ ‾ ‾
So if you call the method with the index 4 (NodeAt(4)
), it will get the first item (John), decrement the counter (to 3), step to the next item (Paul), decrement again (2), get the next item (George), decrement (to 1), get the next item (Ringo) and then decrement to 0 and this will exit the while, and return the LinkedList Item, at the 4 position (Ringo).
Additionally you might want to check the ElementAt extension method provided by System.Linq to achieve the same:
var linkedList = new LinkedList<string>(new []{"John", "Paul", "George", "Ringo"});
linkedList.ElementAt(3); // this returns you Ringo, note that
// the index is 0-based!