[英]Code Analysis Complains about “CA2000 Dispose objects before losing scope” when I Don't Dispose My MDI Child Form
CA2000 Dispose objects before losing scope CA2000在失去作用域之前处置对象
In method FormMain.barButtonItem1_ItemClick(object, ItemClickEventArgs)
在方法
FormMain.barButtonItem1_ItemClick(object, ItemClickEventArgs)
Call System.IDisposable.Dispose on object 'frm' before all references to it are out of scope. 在对对象'frm'的所有引用超出范围之前,请调用System.IDisposable.Dispose。 Winpro FormMain.cs 32
Winpro FormMain.cs 32
Method : 方法 :
private void barButtonItem1_ItemClick(object sender, ItemClickEventArgs e)
{
FormCustomerList frm = new FormCustomerList();
frm.MdiParent = this;
frm.Show();
}
This is not a serious problem, but why is this fired? 这不是一个严重的问题,但是为什么会这样呢?
I can't use finally frm.Dispose()
or using()
because form will not be shown. 我最终不能使用
frm.Dispose()
或using()
因为将不会显示表单。
I have also tried to handle form closing and then dispose but violation is always here. 我也曾尝试处理表单关闭然后进行处理,但违规始终在这里。
Code Analysis can't tell that frm
is still doing anything after it exits scope. 代码分析无法判断
frm
退出作用域后仍在执行任何操作。 In this specific case, the object needs to stay alive after the function is done with it. 在这种特定情况下,完成功能后,对象需要保持活动状态。
The "correct" way to handle this is to maintain a reference to frm
in the parent form. 处理此问题的“正确”方法是在父表单中维护对
frm
的引用。 This reference can then be disposed in the Dispose()
method of the parent form. 然后可以将该引用放在父窗体的
Dispose()
方法中。
private FormCustomerList frm;
private void barButtonItem1_ItemClick(object sender, ItemClickEventArgs e)
{
frm = new FormCustomerList();
frm.MdiParent = this;
frm.Show();
}
If you have multiple sub forms that can be created (which is likely if you're using MDI), you can maintain a List<>
of child forms. 如果您可以创建多个子表单(如果使用的是MDI,则可能会出现这种情况),则可以维护子表单的
List<>
。
private List<FormCustomerList> frms = new List<FormCustomerList>();
private void barButtonItem1_ItemClick(object sender, ItemClickEventArgs e)
{
FormCustomerList frm = new FormCustomerList();
frms.Add(frm);
frm.MdiParent = this;
frm.Show();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.