关闭所有打开的窗体,但C#中的主菜单除外 [英] Close all open forms except the main menu in C#

查看:69
本文介绍了关闭所有打开的窗体,但C#中的主菜单除外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用

FormCollection formsList = Application.OpenForms;

带有foreach循环并说

with a foreach loop and saying,

if (thisForm.Name != "Menu") thisForm.Close();

工作正常,它会跳过菜单,然后关闭第一个菜单,但随后会出错:

Which works ok, it skips the menu, and closes the first, but it then errors:

集合已修改;枚举操作可能无法执行

Collection was modified; enumeration operation may not execute

然后停止.我已经尝试了几个地方,他们都说这个foreach循环是这样做的方法,这特别令人讨厌,因为我关闭表单后不更新表单列表,我认为这可能行得通.我唯一能想到的就是从后头开始,并花一段时间进行前进.

and stops. I have tried a few places, and they all say that this foreach loop is the way to do it, and it is especially annoying as I am not updating my forms list after closing the forms, which I thought might work. The only thing I could think of was to start at the back and work forward using a while.

推荐答案

如果使用foreach枚举集合,则在迭代过程中不能对其进行修改(添加或删除项目).尝试将对表单的引用复制到另一个集合中,然后通过遍历该集合来删除它们.

If you use foreach to enumerate through a collection, it can't be modified (items added or removed) during the iteration. Try copying references to the forms to another collection, and then remove them by iterating through that collection.

在这种情况下,您可以使用列表或简单数组,例如:

In situations like this, you can use a list or a simple array, such as:

List<Form> openForms = new List<Form>();

foreach (Form f in Application.OpenForms)
    openForms.Add(f);

foreach (Form f in openForms)
{
    if (f.Name != "Menu")
        f.Close();
}

或者您可以使用for循环:

Or you can use a for loop:

for (int i = Application.OpenForms.Count - 1; i >= 0; i--)
{
    if (Application.OpenForms[i].Name != "Menu")
        Application.OpenForms[i].Close();
}

或者,我最近和现在的最爱,您可以使用Reverse()方法:

Or, my new and current favorite, you can use the Reverse() method:

foreach (Form f in Application.OpenForms.Reverse())
{
    if (f.Name != "Menu")
        f.Close();
}

这篇关于关闭所有打开的窗体,但C#中的主菜单除外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆