What does "_instance = this;" mean? [closed]
I am taking over a c# windows project. In the startup object app(), there is _instance = this;
. What does it mean? Is it just for a instance and can be used by other method like shutdown etc? Is this something to force singleton? If yes, how does it force to only have one instance?
_instance is defined as below:
private static App _instance;
Source codes are here:
public partial class App : Application
{
private static App _instance;
private SplashView _splashView;
public App()
{
if (!NetworkConnectivityManager.CheckConnectivity())
{
Shutdown();
return;
}
try
{
try
{
AppServiceManager.Start();
}
catch
{
Retryer.DoWithRetries(delegate()
{
ActivateOtherInstance();
Shutdown();
return;
}, 4, 1000);
}
ShowSplashScreen();
ShutdownMode = ShutdownMode.OnExplicitShutdown;
_instance = this;
ExceptionManager.SubscribeToUnhandledAppDomainException();
}
catch (Exception ex)
{
ExceptionManager.HandleException(ex);
}
}
public static void ShutdownApp()
{
_instance.Shutdown();
}
Please let me know if they are enough to tell. Thanks a lot.
If you ask about how to make a class singleton in C#
class A
{
private static readonly A _instance = new A();
public virtual A instance
{
get
{
return _instance;
}
}
private A()
{
}
}
That is a typical way to make singleton in C#.
For your code, it depends how to use it. For singleton, it doesn't make any sense.
Ok, I read your code.
It is simply a bad design. It is used for calling shutdown without have the pointer to a instance of the class.
If you happened to new this class somewhere else, calling App.Shutdown won't shutdown all the App.
If you only create one App class, rewrite it with a proper singleton. If you have multiple App instance running at the same time, rewrite it with a proper instance manager.
Without other logic in the class somewhere, that kind of variable declaration is redundant and unnecessary, since any other method, like shutdown, can reference this
just as easily.
精彩评论