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

时间:2014-07-05 19:11:19

标签: c# loops menustrip

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

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;
    }

然而,无论出于何种原因,似乎在修改drive [currentSlot] .Name时循环退出。为什么要这样做?

2 个答案:

答案 0 :(得分:2)

因为您忘记初始化drives[currentSlot]。它为null并且您得到一个异常( System.NullReferenceException

 drives[currentSlot] = new ToolStripMenuItem();

答案 1 :(得分:0)

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

drives[currentSlot] = new ToolStripMenuItem();

在循环开始时。