Winforms设计师生成的组件IContainer的用途是什么?

时间:2011-02-21 17:52:50

标签: c# winforms dispose designer

在Visual Studio中创建新表单时,设计器会在.Designer.cs文件中生成以下代码:

  /// <summary>
  /// Required designer variable.
  /// </summary>
  private System.ComponentModel.IContainer components = null;

  /// <summary>
  /// Clean up any resources being used.
  /// </summary>
  /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
  protected override void Dispose(bool disposing)
  {
     if (disposing && (components != null))
     {
        components.Dispose();
     }
     base.Dispose(disposing);
  }

components变量的目的是什么?我的理论是,我应该将它用于我的表单拥有的任何IDisposable类,我在Designer之外创建(因为Dispose已经由Designer实现了。)

因此,例如,如果我的表单拥有字体,我可以通过将其添加到components来确保它被处理掉:

  public partial class Form1 : Form
  {
      Font coolFont;

      public Form1()
      {
          InitializeComponent();
          this.coolFont = new Font("Comic Sans", 12);
          components.Add(this.coolFont);
      }
  }

这是它的用途吗?我无法找到任何关于此的文档或信息。

2 个答案:

答案 0 :(得分:23)

当您向表单添加非UI组件(例如Timer组件)时,components将成为这些组件的父级。设计器文件中的代码确保在处理表单时处理这些组件。如果您尚未在设计时将任何此类组件添加到表单,components将为null

由于components是设计器生成的,如果您在表单上没有非UI组件(在设计时),它将是null,我个人会选择以其他方式管理这些组件,将它们放置在靠近或类似的地方。

答案 1 :(得分:21)

组件变量等同于表单的Controls变量。它跟踪所有表单上的控件。因此,表格可以在关闭时自动处理所有控件,这是一项非常重要的清理任务。

表单类没有等效成员跟踪设计时在其上删除的所有组件,因此设计人员会自动处理它。

请注意,将Dispose()方法从Designer.cs文件移动到主窗体源代码文件是完全可以接受的。我强烈建议你这样做,没有理由以任何方式使Form类“特殊”,它只是一个托管类,就像任何其他类。在base.Dispose调用之前,根据需要添加Dispose()调用来处理成员。