There is开发者_如何学JAVA a class library used by some application. It contains a class A for external usage with a static field of another private class B inside the library. User application uses instances of class A from the library.
As the application shutdowns I'd like to perform some clean up in class B. Is it possible to catch application shutdown event in class B without any action from user application?
class B
{
public B()
{
// attach Handler() to applicaiton shutdown event
}
void Handler()
{
// do some work
}
}
using System.Windows.Forms;
public class B
{
public B()
{
Application.ApplicationExit += new EventHandler(Application_ApplicationExit);
}
void Application_ApplicationExit(object sender, EventArgs e)
{
//do cleanup of your class
}
}
If I understand this correctly, your model looks like this:
You would then like to have ClassB
communicate with Application
through ClassA
like shown below:
From an object-oriented design standpoint, this violates the Law of Demeter, which states that objects should only talk to their direct neighbors. In this regard I would suggest you to do the cleanup in ClassA
, if possible.
From an implementation point of view, I would let ClassA
explicitly state its dependency on Application
by taking an instance of it in the constructor. This way you could easily subscribe to any events published by Application
inside ClassA
or, potentially, ClassB
since inner classes in C# can access the outer class' private members:
public class A
{
private readonly Application application;
public A(Application application)
{
if (application == null)
{
throw new ArgumentNullException("application");
}
this.application = application;
this.application.ApplicationExit += application_ApplicationExit;
}
private void application_ApplicationExit(object sender, EventArgs e)
{
// Perform cleanup
}
}
精彩评论