c# - Winforms 设计器生成的组件 IContainer 的用途是什么?

标签 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 变量的用途是什么?我的理论是,我应该将它用于我的表单拥有的任何我在 Designer 之外创建的 IDisposable 类(因为 Dispose 已经由 Designer 实现)。

因此,例如,如果我的表单拥有一种字体,我可以通过将它添加到 components 中来确保它得到处理,如下所示:

  public partial class Form1 : Form
  {
      Font coolFont;

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

这是为了什么?我找不到关于此的任何文档或信息。

最佳答案

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

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

关于c# - Winforms 设计器生成的组件 IContainer 的用途是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5069391/

相关文章:

c# - Automapper - 为什么要使用 Mapper.Initialize?

c# - C#反名练习如何理解?

c# - 使WinForms富文本框忽略 "CTRL + >"和 "CTRL + <"热键

c# - 如何动态创建 View ?

F#:处置闭包内部的资源?

wpf - WPF/Winforms/ClickOnce/的统计使用情况

c# - 如何在 Windows 窗体中获取窗体的所有控件?

c# - 遍历子控件时避免无限循环

asp.net - EF、UoW 和存储库 - 何时在 WebForms 中处理 UnitOfWork?

C#:在调用 Bitmap.save() 后 Dispose() 一个 Bitmap 对象?