"Static constructor" is typically used for initialization when the class is used for the first time. Note that "the first time" means that it is executed only once. Some people have said, isn't class initialization a constructor? A constructor is executed when an instance is declared. It belongs to every instance, but the static constructor belongs to this class. For example, the number of students enrolled in 2013 is "13xxxx ". Therefore, the initial value 13xxxx is a common sacrifice of this student group, not a student. Student IDs and names are all unique attributes of a student. According to the characteristics that the static constructor only executes once, the school student management system writes the "130001" number in a configuration file, and the school management system immediately reads the number as soon as it runs, look at the management system. Oh, let me start from 130001! When writing code, let's first create a student class
Class Student {// first create an attribute for this class: the starting Student ID private static int _ startNumber; // The static constructor is used to read the Starting number set in the configuration file or database. Static Student () {_ startNumber = 130001; // assume that we read the 130001} // Student ID field private int _ code from the configuration file; // Student ID attribute public int Code {get {return _ code;} set {_ code = value ;}// the Student ID increases by 1 public Student () each time an instance object is attached () {this. _ code = (_ startNumber ++ );}
Let's try two students:
class Program { static void Main(string[] args) { Student s1 = new Student(); Console.WriteLine(s1.Code); Student s2 = new Student(); Console.WriteLine(s2.Code); } }
Result: 130001130002