我最近注意到 Visual Studio Designer (C#) 的一些我不理解的行为,想知道是否有人可以澄清...
在我的一些 Windows 窗体中,设计器生成的代码的第一行是这样的;
this.components = new System.ComponentModel.Container();
在这种情况下,dispose 方法在同一个设计器文件中,dispose 方法在 case“if”条件下放置两个“Dispose”调用,如下所示;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
base.Dispose(disposing);
}
}
即除非 disposing 为真且组件不为空,否则不会调用任何内容。
在某些其他表单上,设计器生成的代码中的第一行缺失。在这些情况下,base.Dispose 调用在“if”条件之外......
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
我在跟踪表单未关闭的错误时注意到了这一点,其中 this.components 为空,但 base.Dispose 调用在该条件内(我怀疑设计器代码已被篡改,但这是另一回事。
是什么控制了这种行为?
(项目中的一些早期表单是在 VS 2005 中创建的,我们现在使用 VS 2008 - 线索?)
最佳答案
这是可重现的行为。当您创建一个新表单时,它从一个包含 this.components 构造函数调用的框架开始。当您随后添加一个组件(比如一个计时器)并再次将其删除时,设计器会重新生成代码,现在没有构造函数调用。那不是错误。
首先,骨架代码由Common7\IDE\ItemTemplates\CSharp\Windows Forms\1033\Form.zip\form.designer.cs
生成
在 if() 语句中看到 base.Dispose() 调用是一个错误。这可能是 self 诱导的。或者它可能是框架代码的测试版。 VS2005 做对了。请检查 ItemsTemplatesCache 文件夹。
关于c# - 为什么 Visual Studio IDE 有时会初始化“this.components 对象 : and other times not?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/555526/