“集合已修改;枚举操作可能无法执行。”关于表格处置
“集合已修改;枚举操作可能无法执行。”似乎是 foreach 循环的常见错误,但我无法弄清楚我的错误。我有两类表格。一个在启动时开始,一个按钮创建第二个表单的新实例,并显示它们。当我关闭辅助表单时,我收到一个InvalidOperationException
。
FirstForm.cs
public partial class FirstForm : Form
{
SecondForm frmSecond;
...
private void button1_Click(object sender, EventArgs e)
{
frmSecond= new SecondForm ();
frmSecond.Show();
}
}
SecondForm.designer.cs
partial class SecondForm
{
...
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing); // InvalidOperationException thrown here.
}
}
"Collection was modified; enumeration operation may not execute." appears to be a common error with foreach
loops, but I can't figure mine out. I have two classes of forms. One is begun on startup, and a button creates new instances of the second form, and displays them. When I close the secondary forms, I get an InvalidOperationException
.
FirstForm.cs
public partial class FirstForm : Form
{
SecondForm frmSecond;
...
private void button1_Click(object sender, EventArgs e)
{
frmSecond= new SecondForm ();
frmSecond.Show();
}
}
SecondForm.designer.cs
partial class SecondForm
{
...
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing); // InvalidOperationException thrown here.
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
难道是递归调用Dispose?你能看一下异常发生时的调用堆栈吗?
如果是这种情况,损坏的集合将是表单上的控件集合
Can it be that it calls Dispose recursively? Can you have a look at the call stack when the exception occurs?
If this is the case, the broken collection would be the collection of controls on the form
如果您单击多次,那么 FirstForm 中的引用可能不再指向您要关闭的任何内容。
尝试
If you click multiple times, then the reference in FirstForm may no longer point to whatever you are closing.
try
问题是我放置在第二个表单上的
PowerPacks.RectangleShape
对象,但忘记了(因为它不会渲染)。我删除了该对象,表单处理得很好。进一步测试,我发现任何需要 PowerPacks.ShapeContainer 的控件(
LineShape
、OvalShape
和RectangleShape
,) 会导致此问题,但其他PowerPacks
对象不会。我不确定为什么会发生这种情况,所以如果有人找到解决方法,我将不胜感激。但现在我将避免使用
PowerPacks
形状。The problem was a
PowerPacks.RectangleShape
object I had placed on my second form and forgot about (because it wouldn't render.) I deleted the object, and the form disposed just fine.Testing this further, I found that any control which requires a
PowerPacks.ShapeContainer
(LineShape
,OvalShape
, andRectangleShape
,) cause this problem, but otherPowerPacks
objects don't.I'm not sure why this happens, so if anyone figures out a workaround, I'd appreciate that. But for now I'll avoid
PowerPacks
shapes.