【问题标题】:C# nullReferenceException while adding items to arrayC# nullReferenceException 将项目添加到数组
【发布时间】:2011-11-16 20:04:15
【问题描述】:

当我尝试将项目添加到数组时出现此错误,它会毫无问题地添加 1 个项目,但是当有更多项目时它会停止并给出错误。

nullReferenceException 对象引用未设置为对象的实例。

public void btnZoek_Click(object sender, EventArgs e)
{
    if (search == false)
    {
        OpenFiles[index] = new AddFileClass();

        System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(Application.StartupPath + "\\Saves");
        System.IO.FileInfo[] rgFiles = di.GetFiles("*.txt");//add only .txt files

        foreach (System.IO.FileInfo fi in rgFiles)
        {
            OpenFiles[index].setNewItem(index, fi.Name, Convert.ToString(di));//send the info to the array (Number, filename, filelocation)
            index++;
        }
        search = true; //make sure it doens'nt add something double
    }
    if (search == true)
    {
        Form3_Zoeken_ frmSearch = new Form3_Zoeken_();
        frmSearch.Show();
    }
}

这里有一张图片显示 fi(FileInfo) 和 di(DirectoryInfo) 不为空:

【问题讨论】:

  • 我们是否应该猜测你所有的类都做了什么,哪一行导致了异常以及哪个变量是null?这游戏一天比一天难!
  • 蓝调:我认为 foreach 中的 OpenFiles[index] 包含 null 而不是实例。

标签: c# arrays nullreferenceexception


【解决方案1】:

在我看来,您从未初始化 OpenFiles 数组项 - 也就是说,您只初始化第一项。

试试这个:

public void btnZoek_Click(object sender, EventArgs e)
{
    if (search == false)
    {
        System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(Application.StartupPath + "\\Saves");
        System.IO.FileInfo[] rgFiles = di.GetFiles("*.txt");//add only .txt files

        foreach (System.IO.FileInfo fi in rgFiles)
        {
            OpenFiles[index] = new AddFileClass();
            OpenFiles[index].setNewItem(index, fi.Name, Convert.ToString(di));//send the info to the array (Number, filename, filelocation)
            index++;
        }
        search = true; //make sure it doens'nt add something double
    }
    if (search == true)
    {
        Form3_Zoeken_ frmSearch = new Form3_Zoeken_();
        frmSearch.Show();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-25
    • 2011-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多