问题
When I add IDisposable class member to Windows Forms Form class, I add disposing code to Form's Dispose method. What should I do when I add IDisposable class member to WPF Window class, which is not IDisposable?
回答1:
Extend your window class so that it has IDisposable, then implement the Dispose() method as before:
public class MyWindow : Window, IDisposable
{
public void Dispose()
{
// Dispose your objects here as before.
}
}
回答2:
Approaches you can use:
- Use
Closedevent onWindow. - Implement
IDisposableinterface yourself for thisWindow.
回答3:
You could implement the IDisposable pattern that hooks into the classes finalizer. This means that your IDisposable member would always get cleared up. The only problem is that you wouldn't know when as it depends on the GC to collect the Window class.
Alternatively you could add an event handler the the Window.Closed event and do your disposing there.
来源:https://stackoverflow.com/questions/4450904/idisposable-member-of-wpf-window-class