WPF window class destruction
I create a window like this:
if (someCondition开发者_开发知识库)
{
MyWindow wnd = new MyWindow();
wnd.Owner = this;
wnd.ShowDialog();
}
I want MyWindow's destructor to be called at the closing curly bracket, but it doesn't. Do I need to call something like delete/destroy for MyWindow's destructor to be called?
The "destructor" or finalizer as it is called in C# is called whenever the Garbage Collector feels like. You can trigger the Garbage Collector manually using System.GC.Collect(), but you probably don't want to do this. If your talking about Dispose() on the other hand you can make this being called by creating the window in a "using" clause:
using (var wnd = new MyWindow())
{
wnd.Owner = this;
wnd.ShowDialog();
}
This would make wnd.Dispose() be called when the using clause is done, and would basically be the same as writing:
var wnd = new MyWindow();
wnd.Owner = this;
wnd.ShowDialog();
wnd.Dispose();
About the usage of the IDisposable interface this question might be helpful - and several more on StackOverflow.
using (MyWindow wnd = new MyWindow())
{
wnd.Owner = this;
wnd.ShowDialog();
}
This will call Dispose
on your window after the curly brace, which is what I think you are looking for. Your MyWindow
class will need to implement IDisposable
.
One little thing, you're opening the window and then wanting call it's destructor. That doesn't really make sense. You should close the Window and then it's destructor will be called implicitly.
If you want to call it explicitly you should override Dispose in your MyWindow class. There you can clean up any resources that you want to explicitly dispose off.
精彩评论