when we want to initialize some static variables, we need to use a static constructor. This static constructor belongs to the class, not to the instance, which means that the constructor is only executed once, i.e. it is called automatically by. NET before the first instance is created or any static members are referenced.
Now there's a scenario: Provide a static method, which is used in different places, involves a different parameter value, and everything else is exactly the same. If the content of the static method is copied out into another method, the code redundancy is too much, the practice is not advisable. By using static constructors to handle static variables, you can simplify the code to the greatest extent possible. The following example:
/// <summary>///base class/// </summary> Public classa{ Public Static stringField ="original-test"; //Static Constructors StaticA () {Field="test-a"; } Public Static voidTest () {Console.WriteLine ("The output is:"+Field); }}/// <summary>///sub-class/// </summary> Public classb:a{//Static Constructors StaticB () {Field="Test-b"; } Public Static New voidTest () {a.test ();///Call the base class method, which is important for overwriting the base class Test function, without which the call to B.test () is actually called the test method of the base class.
} }
As shown in the code, type B inherits from base type A. The static constructor in B assigns a static variable field, which is called before the test method in the subclass is called, and the implementation of the test method in B is a full call to the test method of base class A, so that, when the method executes, The static variable used in the Method field is the value of the test-b after the assignment in the static constructor of B.
The result of the call is as follows:
Static void Main (string[] args) { a.test (); // outputs the output is:test-a B.test (); // outputs the output is:test-b console.readline ();}
A.test () Call, field value is Test-a, and B.test () is called, field value is Test-b.
Thus, when the implementation logic of a static method is complex, it is possible to simplify the code for the need to personalize the method: Subclasses reassign static variables in static constructors, and then re-implement static methods in the base class.
(Note that the subsequent re-implementation of the static method in the base class is necessary, otherwise output b.test (), call the base class's Test () method, use the field variable is a variable in the base class, then the output becomes as follows:)
Static void Main (string[] args) { a.test (); // outputs the output is:test-a B.test (); // outputs the output is:test-a. Because there is no overriding subclass method, it is equivalent to A.test () console.readline ();}
C # static Constructors use