Learn a classic example and code of c sharp static functions and variables

  • 2020-05-05 11:45:45
  • OfStack

(1) used for initialization of static fields, read-only fields, etc.                
(2) add the static keyword. You cannot add an access modifier because the static constructor is private.          
(3) the class's static constructor is executed at most once in a given application domain: the static constructor  
is fired only when an instance of the class is created or any static member of the class is referenced (4) static constructors are not inheritable and cannot be called directly.              
(5) if the class contains the   Main   method to start execution, the static constructor for the class will be executed before the   Main   method is called. Any static field with initializers executes those initializers in textual order before executing the static constructor for that class.    
(6) if a static constructor is not written and the class contains a static field with initialization, the compiler automatically generates the default static constructor.
The following example code further illustrates:

/**************************************************  
*  static   state   constitutive   build   letter   The number   practice   xi   
*  ( 1 ) (1) (2) (3)... In order of execution   
*  ( 2 ) output results:  static A()  
* static B()  
* X = 1, Y = 2  
***************************************************/  
using System;  
class A  
{  
public static int X;  
static A() // (4)   Return to after execution   
{  
X = B.Y + 1;  
Console.WriteLine("static A()");  
}  
}  
class B  
{  
public static int Y = A.X + 1; // 3.   Call the A Static member of ,  
//  Go to the A Static constructor ---->  
static B() // 2.   If a static field with an initializer ,  
//  When the static constructor of the class is executed ,  
//  First, execute the initializers in textual order.   
//  Go to the initializer ---->  
{  
Console.WriteLine("static B()");  
}  
static void Main() // 1.   Program entrance ,  
//  If the class contains the one used to start the execution  Main  methods ,  
//  The static constructor of the class will be called  Main  Method before execution.   
//  Go to the B Static constructor ---->  
{  
Console.WriteLine("X = {0}, Y = {1}", A.X, B.Y);// 5.   The output   
Console.ReadLine();  
}  
} 

Related articles: