我已经阅读了本文中的 IDisposable模式,并希望在我的Windows窗体应用程序中实现它.我们知道在windows表单.Designer.cs类中已经存在Dispose方法
private System.ComponentModel.IContainer components = null;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
Run Code Online (Sandbox Code Playgroud)
在.cs类我正在使用Typed Dataset来读取和保存数据.
public partial class frmCustomerList
{
private MyTypedDataSet ds = new MyTypedDataSet();
...
}
Run Code Online (Sandbox Code Playgroud)
那么,如何实现IDisposable配置MyTypedDataSet?如果我IDisposable在frmCustomerList中实现并实现其接口
public partial class frmCustomerList : IDisposable
{
private MyTypedDataSet ds = new MyTypedDataSet();
void Dispose()
{
ds.Dispose();
}
}
Run Code Online (Sandbox Code Playgroud)
那么Dispose(bool disposing).Designer.cs中的方法呢?
如果您在Designer.cs文件中查找并在dispose方法下面查找,您将看到以下内容
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
Run Code Online (Sandbox Code Playgroud)
仅InializeComponent()警告您不要修改。您可以剪切(而不是复制)并将其粘贴到protected override void Dispose(bool disposing)设计器文件之外,然后将其移动到您的主代码文件中,而不必担心,只需确保将components.Dispose();零件保留下来,因为通过设计器添加的所有一次性对象都将放入该收藏夹中。处理。
public partial class frmCustomerList
{
private MyTypedDataSet ds = new MyTypedDataSet();
protected override void Dispose(bool disposing)
{
ds.Dispose();
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
//The rest of your frmCustomerList.cs file.
}
Run Code Online (Sandbox Code Playgroud)
我将使用其中一个表单事件来处理表单的任何成员,例如
http://msdn.microsoft.com/en-us/library/system.windows.forms.form.onlined(v=vs.110).aspx
例如
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
if (ds != null)
ds.Dispose();
}
Run Code Online (Sandbox Code Playgroud)