2016-11-27 249 views
-2

所以即時製作一個程序,我有一個LinkedList類,我必須將其實現到一個Forms應用程序。唯一困難的部分是使ToString方法正常工作,它不會。爲什麼我的ToString方法總是返回一個NullReferenceException?

public override string ToString() 
    { 
     ListNode temp = head; 
     string modifier = ""; 
     for (int i = 0; i <= count -1; i++) 
     { 
      modifier += count + ") " + temp.getValue() + "\r\n"; 
      temp = temp.getNext(); 
     } 
     return modifier; 
    } 

我認爲這樣做是因爲頭開始爲空,因爲列表開始空,但我只是不知道。任何幫助,將不勝感激。如果您需要查看其他代碼行,請不要樂意提供。

+4

沒有回答,當你說你覺得'head'是空你的問題嗎? – NtFreX

+0

@ Dr.Fre你會想,但沒有。如果'head'爲'null',則'count' *應該爲零,在這種情況下'temp'('head')永遠不會被訪問。 – hvd

+1

有一個非常強大的調試工具,稱爲*鼠標*。將鼠標懸停在東西上,它會告訴什麼是空 – Plutonix

回答

0

看起來你的值爲count是錯誤的 - 它不符合列表中有多少個節點。然而,一個更簡單的解決將是使用while循環 - 所以它具有的優勢不那麼冗長:

public override string ToString() 
{ 
    ListNode temp = head; 
    string modifier = ""; 
    while(temp != null) 
    { 
     modifier += count + ") " + temp.getValue() + "\r\n"; 
     temp = temp.getNext(); 
    } 
    return modifier; 
} 

我們還可以添加一個「計數驗證」以確保count實際上是正確的檢測用途:

public int fullCount{ 
    get{ 
     int total=0; 
     ListNode temp = head; 

     while(temp != null) 
     { 
      total++; 
      temp = temp.getNext(); 
     } 

     return total; 
    } 
} 

隨着:

Debug.Assert(fullCount == count,"Count is wrong."); 
相關問題