During this time, I started to look at the design mode. I just looked at the singleton mode. The most concise method to achieve it is: Class Singleton
{
Public Static Readonly Singleton instance = New Singleton ();
Private Singleton ()
{}
}
Many people Code Not very understandable. In fact, they are equivalent:Class Singleton
{
Public Static Readonly Singleton instance;
Static Singleton ()
{
Instance= NewSingleton ();
}
Private Singleton ()
{}
}
Now let's look at the static constructor and see how it is implemented.
A static constructor is used to initialize any static data or perform a specific operation that only needs to be performed once. The static constructor is automatically called before the first instance is created or any static member is referenced ., The method is the same as the instance constructor used to initialize instance data. There are some differences between static constructor and instance constructor rules. Unlike the instance constructor, static constructor cannot be overloaded, so only one default non-parameter static constructor is available for static constructor. Static constructors cannot be explicitly called or inherited from the derived class, but can be called when a base class type is created.
C # principles for using static constructor:
1. The static constructor is called before the class instance is created. Therefore, it is called before all instance constructor instances.
2. The static constructor is called before the first instance of the class is created.
3. The static constructor is called before a static field is referenced.
The following is a simple example: Class Test
{
Static Test ()
{
Console. writeline ("A");
}
Public Test ()
{
Console. writeline ("B");
}
}
Class Testother: Test
{< br> Public testother ()
{< br> console. writeline ( " C " );
}
}
Then:Test T1= NewTest ();
Test T2= NewTest ();
Testother T3= NewTestother ();
Output: A, B, B, B, c
The static constructor is called only once, but this method has a defect in implementing the singleton mode. The constructor cannot contain parameters, but it does not have a great impact.