How do I add Dispose functionality to a C# UserControl?

本秂侑毒 提交于 2019-11-30 10:53:41

问题


I have a class which implements UserControl. In .NET 2005, a Dispose method is automatically created in the MyClass.Designer.cs partial class file that looks like this:

  protected override void Dispose(bool disposing)
  {
     if (disposing && (components != null))
     {
        components.Dispose();
     }
     base.Dispose(disposing);
  }

If I want to add my own Dispose functionality, where would I put it? Since this file is generated, I don't want to add code here and risk it getting blown away.


回答1:


In such a case I move the generated Dispose method to the main file and extend it. Visual Studio respects this.

An other approach would be using a partial method (C# 3.0).




回答2:


All Component classes implement a Disposed event. You can add an event handler for that event and clean up things in there.

For example, in your UserControl you could add following method:

private void OnDispose(object sender, EventArgs e)
{
    // do stuff on dispose
}

And in constructor (or in Load event handler) add the following line:

Disposed += OnDispose;



回答3:


I believe in this case the code-generator honors your code. It should be safe to put it in the codebehind.




回答4:


In VS 2005 (and 2008) you can update the Dispose method and it will not get removed when you edit the control from the designer.




回答5:


You can move it out from the .designer.cs file and into the main .cs file if you want. As has been said already, it won't be overwritten.




回答6:


You just need to overload the public void Dispose() method in the Component Class that the user control inherits.

make sure you pass the call to the base method as well as doing your dispose functionally or you'll break the functionality unless you fully implement it




回答7:


I would think the cleanest way would be to have your control subscribe to its own Disposed() event and do your cleanup in there.




回答8:


there is a Unloaded event for the UserControl that you can use to clean up,



来源:https://stackoverflow.com/questions/167602/how-do-i-add-dispose-functionality-to-a-c-sharp-usercontrol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!