Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
尝试将字符串添加到字符串列表时,C#中出现异常_C#_.net_String_List - Fatal编程技术网

尝试将字符串添加到字符串列表时,C#中出现异常

尝试将字符串添加到字符串列表时,C#中出现异常,c#,.net,string,list,C#,.net,String,List,我在列表中遇到异常。尝试运行此代码时添加行: string searchText = searchByInterestBox.Text; List<string> checkedItems = null; if (m_BusinessLogic != null) { if (searchText != string.Empty) {

我在列表中遇到异常。尝试运行此代码时添加行:

        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());
                    }
string searchText=searchByInterestBox.Text;
列表checkedItems=null;
if(m_BusinessLogic!=null)
{
if(searchText!=string.Empty)
{
尝试
{
interestResultBox.Items.Clear();
foreach(var itemChecked in Interest CheckkedListBox.CheckedItems)
{
Add(itemChecked.ToString());
}
调试时,当到达最后一行代码(checkedItems.Add)时,它会显示“对象引用未设置为对象的实例”

知道我把字符串列表弄错了什么吗

非常感谢。
Itzik.

不应使用空值初始化列表:

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

checkedItems
null
,因此您得到一个异常。您需要初始化它

而不是:

List<string> checkedItems = null;
列表checkedItems=null;
做:

IList checkedItems=new List();

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

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

异常表示您的列表尚未创建(仍然为空)

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