在 C# 中删除丢失的对象

deleting lost objects in c#

这是我创建的 class 创建一个对象的函数:

public static void CreateLabel()
{
     Label myLabel = new Label();
     // changes added to the myLabel
}

现在假设我调用了那个函数。

private void btnShow(object sender, EventArgs e)
{
     MyClass.CreateLabel();
}

完成后如何删除 'myLabel'?

this.Controls.Remove(myLabel); // doesn't recognise myLabel

如果您正在开发 Windows 表单应用程序,则可以使用 Control.ControlCollection.Remove 方法从表单或其他控件中删除控件。您还可以使用 Clear 删除集合中的所有控件。

您可以使用 Visibility = false,或者您可以使用选项卡控件。