在Winforms上设置控件

jma*_*yor 7 c# winforms

为什么Visual Studio将此代码添加到Class.Designer.cs分部类中.任何人都能告诉我这个组件变量什么时候会得到一些价值?这里的模式是什么?

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)

Jør*_*ode 5

私有字段components用于跟踪表单上的一次性组件.尝试拖动Timer组件,您应该在设计器生成的代码中看到类似的内容:

this.components = new System.ComponentModel.Container();
this.timer1 = new System.Windows.Forms.Timer(this.components);
Run Code Online (Sandbox Code Playgroud)

在所显示的图案Dispose(bool)的方法通常被称为 一次性 图案.基本上,该模式确保所有被跟踪的组件都将被释放,即使您从未Dispose显式调用该方法,在这种情况下,表单的基类将Dispose在其终结器中调用该方法(在垃圾回收期间).


Han*_*ant 5

它是由表单项模板生成的代码(common7\ide\itemtemplates\csharp\windows forms\1033\form.zip\form.designer.cs).它实际上有一个bug,它包含的InitializeComponent()方法不必要地初始化"this.components"变量.如果表单没有任何组件,您可以安全地从代码中删除该语句.如果稍后添加组件,设计器将自动将其放回原处.

另一件不太好的事情是将Dispose()方法放在Designer.cs文件中.它确实属于form.cs文件,因此您可以为表单中应该处理的字段添加Dispose()调用.不要犹豫,自己移动代码,以这种方式修改设计器文件没有任何令人不快的副作用.请远离使用"生成代码"区域括起来的代码.

正如大多数其他答案中所提到的,当表单关闭时,此代码必须调用您在表单上放置的任何组件的Dispose()方法.表格上的控件也需要处理,但这是自动的.Form类通过迭代Controls集合来找回它们.