创建处理程序时退出ForEach循环- c#

本文关键字:循环 ForEach 退出 处理 程序 创建 | 更新日期: 2023-09-27 18:11:39

在我的程序中,我列出了菜单带内的每个逻辑驱动器。为此,我使用以下代码

private ToolStripMenuItem[] getAllDrives()
    {
        //find the number of drives
        int arrayLength = DriveInfo.GetDrives().Count();
        //create array that can hold all drives
        ToolStripMenuItem[] drives = new ToolStripMenuItem[arrayLength];
        //populate array
        int currentSlot = 0;
        foreach (DriveInfo d in DriveInfo.GetDrives())
        {
            drives[currentSlot].Name = d.Name;
            drives[currentSlot].Tag = d.Name;
            drives[currentSlot].Text = d.Name + " " + d.VolumeLabel;
            drives[currentSlot].Click += new EventHandler((se,e1) => driveClick(d.Name));
            currentSlot++;
        }
        return drives;
    }

然而,似乎出于某种原因,当驱动器[currentlot]。修改名称。它为什么这样做?

创建处理程序时退出ForEach循环- c#

因为您忘记初始化drives[currentSlot]。它是空的,你得到一个异常(System.NullReferenceException)

 drives[currentSlot] = new ToolStripMenuItem();

在尝试访问其属性之前,您没有在drives[currentSlot]初始化项目,因此您可能会抛出NullReferenceException,从而终止循环。尝试添加:

drives[currentSlot] = new ToolStripMenuItem();