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

ben*_*sai 34 c# dispose designer winforms

在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);
  }
Run Code Online (Sandbox Code Playgroud)

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);
      }
  }
Run Code Online (Sandbox Code Playgroud)

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

Fre*_*örk 24

将非UI组件添加到表单(例如Timer组件)时,components将是这些组件的父组件.设计器文件中的代码确保在处理表单时处理这些组件.如果您还没有在设计时components将任何此类组件添加到表单中,那么null.

既然components是设计师生成的,并且null如果你在表单上没有非UI组件(在设计时),我个人会选择以其他方式管理这些组件,将它们放在表格附近或类似的东西上.

  • 我通过从设计器中添加一个SerialPort组件,在设计器生成的代码中设置组件实例变量.所以我现在明白了.我希望它不会在没有使用时生成组件和Dispose代码,这样可以避免混淆并导致更少的代码,但是whatchucando (2认同)

Han*_*ant 22

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

表单类没有等效成员,可以跟踪设计时放在其上的所有组件,以便设计人员自动处理它.

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

  • 很高兴知道将Dispose移出Designer.cs文件是可以接受的. (10认同)