c# - 如何在 Windows 窗体上使用 IDisposable 模式

标签 c# idisposable

我在 article 上读到了 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);
}

在 .cs 类中,我使用类型化数据集来读取和保存数据。

public partial class frmCustomerList
{
    private MyTypedDataSet ds = new MyTypedDataSet();
    ...
}

那么,如何实现IDisposable来处理MyTypedDataSet呢?如果我在 frmCustomerList 中实现 IDisposable 并实现它的接口(interface)

public partial class frmCustomerList : IDisposable
{
    private MyTypedDataSet ds = new MyTypedDataSet();
    void Dispose()
    {
       ds.Dispose();
    }
}

.Designer.cs 中的 Dispose(bool disposing) 方法怎么样?

最佳答案

如果您查看 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()
    {

只有 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.
}

关于c# - 如何在 Windows 窗体上使用 IDisposable 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23690618/

相关文章:

c# - 为什么 this.close() 关闭应用程序

c# - 将 HTML 添加到 XElement

.net - 在这种情况下,.Net 会为我调用 Dispose 吗?

c# - PdfStamper正在处理输出流吗? (iTextSharp)

c# - 已处置的任务会发生什么?

c# - 带有附件上传和电子邮件发送的表格

c# - 单元测试私有(private)方法

c# - ID一次性级联

c# - 我将如何在这种情况下实现 IDisposable?

c# - 为什么我的射弹没有绘制在屏幕上?