c# - 为什么 Visual Studio IDE 有时会初始化“this.components 对象 : and other times not?

标签 c# visual-studio winforms visual-studio-2008 visual-studio-2005

我最近注意到 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/

相关文章:

.net - WinForms 中具有 alpha channel 透明度/不透明度的启动屏幕

c# - 编码数字,z-base-32 的 C# 实现或其他?

c# - MSBuild 2015 发布 : Can't find the valid AspnetMergePath

c# - Azure 函数 - 函数应该写在静态类中吗

c# - 这是在多线程方法中安全使用 Dictionary 吗?

visual-studio - 您使用什么Visual Studio加载项?

c# - 如何在多显示器环境中轻松找到表单位置的屏幕位置?

winforms - 为什么Richtextbox无法正确显示此表?

c++ - 许多变量的数据交换

visual-studio-2010 - 安装Visual Studio 2012发行预览版后出现错误 'LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt'