创建处理程序时ForEach循环将退出-C#
在我的程序中,我列出了menustrip中的每个逻辑驱动器。 为了实现这一点,我使用以下代码创建处理程序时ForEach循环将退出-C#,c#,loops,menustrip,C#,Loops,Menustrip,在我的程序中,我列出了menustrip中的每个逻辑驱动器。 为了实现这一点,我使用以下代码 private ToolStripMenuItem[] getAllDrives() { //find the number of drives int arrayLength = DriveInfo.GetDrives().Count(); //create array that can hold all drives Tool
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;
}
但是,无论出于何种原因,当修改驱动器[currentSlot].Name时,循环似乎会退出。为什么要这样做?因为您忘记初始化
驱动器[currentSlot]
。它为null,您会得到一个异常(System.NullReferenceException)
在尝试访问项目属性之前,您没有在
驱动器[currentSlot]
处初始化该项目,因此您可能会抛出NullReferenceException
,从而终止循环。尝试添加:
drives[currentSlot] = new ToolStripMenuItem();
在循环开始时。哦,哇。新手犯了我的错误。谢谢为什么你的程序没有出现异常而崩溃?您是否在某处捕获并吞下了异常?@user49096如果有帮助:对于未来的问题,请在姿势中提供异常详细信息-“循环退出”是对问题的非常不具体的解释。就目前而言,你的问题已经在问题的“数组元素”部分得到了回答。我将在以后的文章中更具体地回答。这种情况的奇怪之处在于,没有抛出异常,这使得我很难精确地找出错误的确切原因。“没有抛出异常”是非常不可能的-您可能正在吃掉caller或更高版本中的所有异常。考虑读异常处理的好实践,即启动.@ AlxeILVENKOV,如果在VisualStudio调试会话中的64位环境中调用FultHyLoad事件,这是可能的。
drives[currentSlot] = new ToolStripMenuItem();