2011-06-18 60 views
0

試圖運行該代碼時,我得到了List.Add線異常:異常在C#試圖將字符串添加到字符串列表時

 string searchText = searchByInterestBox.Text; 
     List<string> checkedItems = null; 

     if (m_BusinessLogic != null)  
     { 
      if (searchText != string.Empty) 
      { 
       try 
       { 
        interestResultBox.Items.Clear(); 
        foreach (var itemChecked in InterestsCheckedListBox.CheckedItems) 
        { 
         checkedItems.Add(itemChecked.ToString()); 
        } 

在調試,達到了代碼的最後一行時( checkedItems.Add)它說「對象引用未設置爲對象的實例」

任何想法我做了什麼錯誤的字符串列表?

非常感謝。 Itzik。

回答

5

checkedItemsnull,所以你得到一個例外。你需要初始化它。

相反的:

List<string> checkedItems = null; 

務必:

IList<string> checkedItems = new List<string>(); 
1

你不應該初始化空列表:

List<string> checkedItems = new List<string>(); 
1

你從來沒有創建的列表中的一個實例,請嘗試:

List<string> checkedItems = new List<string>(); 
1

的異常意味着你的名單尚未尚未創建(並且仍爲空)。

List<string> checkedItems = new List<string>();