Deep analysis of static variables and static constructors in C #:
In the routine development process, it is often used to static variables, known as static variables when the resident memory of the variable, its life cycle from the beginning of initialization until the end of application. However, we often ignore the initialization time of static variables. An in-depth look at how the static variable is initialized.
A static variable is defined in a class, and the class is bound to have a static constructor, whether we define a static constructor or a static constructor, and if we do not define a static constructor, the compiler will automatically give us a default static constructor. The execution time of the initialization of the static variable of the class is the time when the static constructor executes, so finding the execution time of the static constructor is equal to finding the time when the static variable is initialized. The execution time of a static variable is executed at the time of the first instance of new class or when any static member of the class is referenced for the first time, and the static constructor is. NET calls itself, and will only be called once, the following piece of code helps children to carefully study the timing of the static face-changing call:
Public classfirstclass{ Public Static int_firstval=1; StaticFirstClass () {_firstval= Secondclass._secondval +1; }} Public classsecondclass{ Public Static int_secondval; StaticSecondclass () {}Static voidMain () {Console.WriteLine ("firstval={0}, Secondval={1}", Firstclass._firstval, Secondclass._secondval); Console.ReadLine (); }}View Code
The above code, before the static constructor of FirstClass _firstval to the default value of 0, after the completion of the static constructor _firstval is 1, the result of the program run output is: firstval=1,secondval=2. And the static constructor of the above code FirstClass is executed before the static constructor of the Secondclass.
Deep understanding of static and static constructors in C #