c# - 我需要在处理完控件后删除控件吗?

标签 c# .net .net-2.0 controls dispose

.NET 2

// dynamic textbox adding
myTextBox = new TextBox();
this.Controls.Add(myTextBox);

// ... some code, finally

// dynamic textbox removing
myTextBox.Dispose();

// this.Controls.Remove(myTextBox); ?? is this needed

小解释

  • 当然,如果我Dispose 一个控件,我将不再看到它,但无论如何,它在父控件集合中仍将是“Nothing”吗?
  • 我还需要按照 MSDN 的建议,从控件中删除所有处理程序吗?

最佳答案

不,你不知道。
我试过了。

您可以将以下代码粘贴到LINQPad 中:

var form = new Form();
var b = new Button();
form.Controls.Add(b);
b.Click += delegate { b.Dispose(); };
Application.Run(form);

编辑:控件从表单的Controls 集合中删除。为了演示这一点,请将点击处理程序替换为以下内容:

b.Click += delegate { b.Dispose(); MessageBox.Show(form.Controls.Count.ToString());};

它将显示 0

2nd 编辑:Control.Dispose(bool disposing) 包含以下代码:

                if (parent != null) { 
                    parent.Controls.Remove(this); 
                }

关于c# - 我需要在处理完控件后删除控件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2013877/

相关文章:

c# - 在 C# 中使用 Aspose.words 按列导航

.net - 如何使用 linq to sql 外部映射延迟加载属性?

c# - 如何在不访问应用程序目录的情况下将程序集从字节数组加载到非默认 AppDomain 中?

c# - win CE 6.0 设备上的按钮

.net - Math.IEEERemainder 返回否定结果。为什么?

c# - 使用 ngen.exe 创建和分发 native 镜像

c# - 进行 SSL 连接时需要主机名验证

c# - TabControl WPF 中的延迟加载数据绑定(bind)列表

c# - 从 .net 客户端获取有关 WCF ssl 证书的到期日期/详细信息

wcf - 从 .Net 2.0 客户端调用 WCF 服务时如何配置安全性