The static constructor is primarily used to initialize the value of static variables. This function is only executed, and it will call it when the object of the first creating classes. You can refer to the code below.
Using system;
Class Welcome {public welcome () {console.writeLine ("Constructor Welcome ()");}
Static Welcome () {Console.WriteLine ("Constructor Static Welcome ()");}
Static void main () {new welcome (); new welcome (); console.readline ();}}
Execution: Constructor Static Welcome () Constructor Welcome () Constructor Welcome ()
Another example, the following code
public class User {static private int count; static public int Count {get {return count;}} public User () {count ;} static User () {count = 0;}} private void Page_Load (object sender, System.EventArgs e) {// Place the user code here to initialize the page response.write ("User count =" user.count; response.write ("
");"); "
User alex = new user ();
Response.write (""
User count = " user.count);
Response.write (""
Creating user rob. ");
User rob = new user ();
Response.write (""
User count = " user.count);
Response.write (""
");"); ");
User jake = new user ();
Response.write (""
User count = " user.count);
}
The execution result of this code is: user count = 0 -------------------------------------- --------------------------------
---------- CREAN ALEX.USER Count = 1 -------------------------------- -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
---------- CREAN ROB.USER Count = 2 -------------------------------- -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
---------- CREANG User Jake.user Count = 3
If some operations are only hoped to be executed. At this time, you can consider using a static constructor. Of course, if you design some objects, that is, use single-piece mode.
The static constructor can be automatically called when any method of the static class for the first time, and the abnormal capture thrown in the static constructor is more troublesome. You can refer to the discussion below: http://community.9cbs.net/expert/topic/3274/3274910.xml Static constructor is automatically called and cannot be explicitly called. Although many constraints are provided, the exact time and order executed by the static constructor is uncertain: a static constructor of a class is executed before any instance of this class. A class static constructor is executed before any static member of the class. A static constructor of a class is executed after the static constructor of all of its derived class. A static constructor of a class will never be executed more than one.