Before you create a type instance, you should initialize all static member variables for that instance. C # provides static initializers and static constructors for this purpose.
A static constructor is a special constructor that will be executed before all other methods are executed and before the variable or property is accessed for the first time.
If you simply allocate space for a member, you can use the initializer syntax instead of a static constructor. If you want to initialize static member variables with more complex logic, you can use a static constructor.
单例模式
Is the most common scenario for a static constructor, just declare the instance constructor private, and then add the initializer:
public class MySingleton{ private static readonly MySingleton theOneAndOnly = new MySingleton(); private MySingleton(){} public static MySingleton TheOnly { get { return theOneAndOnly; } }}
If you have more complex initialization logic for the singleton, you can use the static constructor:
public class MySingleton{ private static readonly MySingleton theOneAndOnly; private MySingleton(){} static MySingleton() { theOneAndOnly = new MySingleton(); //other code... } public static MySingleton TheOnly { get { return theOneAndOnly; } }}
Static constructors have the advantage of catching exceptions when compared to static initializers, because the CLR terminates your program when there is an error in the static constructor and static initializer, and the static constructor that catches the exception can keep the program running, but the disadvantage is that the static constructor can only be initialized once, In the event of an error causing a type to not initialize, the CLR will not attempt to initialize again.
"C # Efficient Programming" Reading notes 13-correct initialization of static member variables