【问题标题】:Exception in C# when trying to add a string to strings List尝试将字符串添加到字符串列表时 C# 中的异常
【发布时间】:2011-06-18 13:30:40
【问题描述】:

尝试运行此代码时,List.Add 行出现异常:

        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) 时,它会显示“对象引用未设置为对象的实例”

知道我对字符串列表做错了什么吗?

非常感谢。 伊齐克。

【问题讨论】:

    标签: c# .net string list


    【解决方案1】:

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

    代替:

    List<string> checkedItems = null;
    

    做:

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

    【讨论】:

      【解决方案2】:

      你不应该用 null 来初始化列表:

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

      【讨论】:

        【解决方案3】:

        您从未创建过列表的实例,请尝试:

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

        【讨论】:

          【解决方案4】:

          异常意味着您的列表尚未创建(并且仍然为空)。

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2018-04-12
            • 1970-01-01
            • 2021-12-05
            • 2019-03-12
            • 1970-01-01
            • 2011-12-15
            • 1970-01-01
            相关资源
            最近更新 更多