2009-02-15 61 views
1

我在這裏做了一個單獨的線程,因爲我相信如果我編寫評論,評論不會將該線程推到頂部,因此會有通知給任何寫過此消息的人線。此代碼的工作原理的解釋

 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; 
    } 
} 

我想知道的,什麼是擴展方法實現:

此代碼是由邁克爾·布恩在螺紋Writing text to the middle of a file供應嗎?

第一遍,x = x。下一個意思是我們看着Ringo而不是George,等等。在發動機蓋下究​​竟發生了什麼以及從調用NodeAt(6)開始,代碼的作用是什麼?我這樣問,因爲能夠閱讀和理解代碼而不使用逐步式方法作爲一種輔助(例如,在工作中,您將閱讀打印文檔中的代碼),這一點很重要。另外,爲什麼我們在循環中向後計數,爲什麼在進入循環體之前有一個括號要減去1?

由於

回答

7

擴展方法只能通過鏈表n元件的步驟,它用列表(l.First),然後在一段時間,它遞減索引的第一個元素初始化x到步驟向前n倍(看x = x.Next;):

 
Index: 1   2   3   4 
    _ _ _ _  _ _ _ _  _ _ _ _ _  _ _ _ _ 
    | John |-> | Paul |-> | George |-> | Ringo | 
    ‾ ‾ ‾ ‾  ‾ ‾ ‾ ‾  ‾ ‾ ‾ ‾ ‾  ‾ ‾ ‾ ‾ 

所以,如果你用食指4(NodeAt(4))的方法,將獲得的第一項(約翰),遞減計數器(3)步到下一個項目(保羅),再次遞減(2),得到下一個項目(喬爾ge),遞減(到1),獲得下一個項目(Ringo),然後遞減到0,這將退出,而返回 LinkedList Item,位於第4個位置(Ringo)。

另外,你可能要檢查由System.Linq的提供的ElementAt擴展方法來實現相同的:

var linkedList = new LinkedList<string>(new []{"John", "Paul", "George", "Ringo"}); 
linkedList.ElementAt(3); // this returns you Ringo, note that 
         // the index is 0-based! 
+0

尼斯ASCII藝術! +1 – Kredns 2009-02-15 21:45:24