Static constructor, java static Constructor
Let's take a look at a common question. What is the execution result of the following code?
class A { public static int X = B.Y + 1; static void Main(string[] args) { Console.WriteLine(X); } } class B { public static int Z = 10; public static int Y; static B() { Console.WriteLine(Z); Y = A.X + 1; } }
I. Definition
According to the name, the static constructor has two features: "static" and "constructor. The first feature determines that it is similar to a static function and can only use static members. The second feature determines that it is similar to a constructor and has initialization function and no return value.
Unlike Constructors (for instance objects), static Constructors (for classes) are executed only once and called before the first instance object is created, therefore, it can be used for operations that only need to be executed once, and it does not allow public modifiers, which are automatically called by the program and cannot be called by the outside world.
Summary: The static constructor is used to initialize any static data or perform only one operation. Before creating the first instance object or referencing any static variables, the static constructor is automatically called.
Features:
1. The static constructor neither has an access modifier nor a parameter.
2. Before creating the first instance or referencing any static member, the static constructor is automatically called to initialize the class.
3. Static constructor cannot be called directly.
4. In a program, users cannot control when to execute static constructor.
5. thread security.
Ii. Syntax
public class StaticTester { static StaticTester() { } }
Iii. Functions
Used to initialize static members. Sometimes we read some values from the configuration file as static variables, such:
public class StaticTester { private static readonly string key = ConfigurationManager.AppSettings["key"]; private static readonly string value = ConfigurationManager.AppSettings["value"]; static StaticTester() { } }
If you want to read more configuration information and add some logic judgment, you can do this:
Public class StaticTester {private static readonly string key; private static readonly string value; static StaticTester () {key = ConfigurationManager. appSettings ["key"]; if (string. isNullOrEmpty (key) {throw new Exception ("the key variable is not correctly configured! ");} Value = ConfigurationManager. receivettings [" value "]; if (string. IsNullOrEmpty (value) {throw new Exception (" the value variable is not correctly configured! ");}}}
Iv. execution sequence
1. initialize static variables first during running.
2. If there is a static constructor, call the static constructor before creating the first instance object or referencing any static variables.
3. Other operations.