Static constructor, java static Constructor
1. The static constructor is used to initialize static data or perform only one special operation.
2. The static constructor neither has an access modifier nor a parameter.
3. Before creating the first instance or referencing any static member, the static constructor is automatically called to initialize the class.
4. The static constructor cannot be called directly.
5. If a static constructor causes an exception, the constructor will not be called again during the runtime, And the type will remain uninitialized during the lifetime of the application domain where the program runs.
Class Program {static void Main (string [] args) {// call the static constructor after bus1 is instantiated. Only one Bus bus1 = new Bus (71) is called ); bus bus2 = new Bus (72); bus1.Drive (); System. threading. thread. sleep (3600); bus2.Drive (); Console. writeLine ("Press any key to exit. "); Console. readKey () ;}} public class Bus {protected static readonly DateTime globalStartTime; protected int RouteNumber {get; set;} static Bus () {globalStartTime = DateTime. now; Console. writeLine ("static constructor sets global start time to {0}", globalStartTime. toLongTimeString ();} public Bus (int routeNum) {RouteNumber = routeNum; Console. writeLine ("Bus # {0} is created", RouteNumber);} public void Drive () {TimeSpan elapsedTime = DateTime. now-globalStartTime; Console. writeLine ("{0} is starting its route {1: N2} minutes after global start time {2}", this. routeNumber, elapsedTime. totalMilliseconds, globalStartTime. toLongTimeString ());}}