2011-06-18 56 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>();