Compartir a través de


Constructores estáticos (Guía de programación de C#)

Un constructor estático se utiliza para inicializar cualquier dato estático o realizar una acción determinada que solo debe realizarse una vez. Es llamado automáticamente antes de crear la primera instancia o de hacer referencia a cualquier miembro estático.

class SimpleClass
{
    // Static variable that must be initialized at run time. 
    static readonly long baseline;

    // Static constructor is called at most one time, before any 
    // instance constructor is invoked or member is accessed. 
    static SimpleClass()
    {
        baseline = DateTime.Now.Ticks;
    }
}

Los constructores estáticos tienen las propiedades siguientes:

  • Un constructor estático no permite modificadores de acceso ni tiene parámetros.

  • Se le llama automáticamente para inicializar la clase antes de crear la primera instancia o de hacer referencia a cualquier miembro estático.

  • El constructor estático no puede ser llamado directamente.

  • El usuario no puede controlar cuando se ejecuta el constructor estático en el programa.

  • Los constructores estáticos se utilizan normalmente cuando la clase hace uso de un archivo de registro y el constructor escribe entradas en dicho archivo.

  • Los constructores estáticos también son útiles al crear clases contenedoras para código no administrado, cuando el constructor puede llamar al método LoadLibrary.

  • Si un constructor estático inicia una excepción, el motor en tiempo de ejecución no lo invocará una segunda vez y el tipo seguirá sin inicializar durante el período de duración del dominio de aplicación donde se ejecuta el programa.

Ejemplo

En este ejemplo, la clase Bus tiene un constructor estático. Cuando se crea la primera instancia de Bus (bus1), se invoca el constructor estático para inicializar la clase. En el resultado del ejemplo, se comprueba que el constructor estático se ejecuta solo una vez, incluso si se crean dos instancias de Bus, y que se ejecuta antes de que se ejecute el constructor de instancia.

    public class Bus
    {
        // Static variable used by all Bus instances. 
        // Represents the time the first bus of the day starts its route. 
        protected static readonly DateTime globalStartTime;

        // Property for the number of each bus. 
        protected int RouteNumber { get; set; }

        // Static constructor to initialize the static variable. 
        // It is invoked before the first instance constructor is run. 
        static Bus()
        {
            globalStartTime = DateTime.Now;

            // The following statement produces the first line of output,  
            // and the line occurs only once.
            Console.WriteLine("Static constructor sets global start time to {0}",
                globalStartTime.ToLongTimeString());
        }

        // Instance constructor. 
        public Bus(int routeNum)
        {
            RouteNumber = routeNum;
            Console.WriteLine("Bus #{0} is created.", RouteNumber);
        }

        // Instance method. 
        public void Drive()
        {
            TimeSpan elapsedTime = DateTime.Now - globalStartTime;

            // For demonstration purposes we treat milliseconds as minutes to simulate 
            // actual bus times. Do not do this in your actual bus schedule program!
            Console.WriteLine("{0} is starting its route {1:N2} minutes after global start time {2}.",
                                    this.RouteNumber,
                                    elapsedTime.TotalMilliseconds,
                                    globalStartTime.ToShortTimeString());
        }
    }

    class TestBus
    {
        static void Main()
        {
            // The creation of this instance activates the static constructor.
            Bus bus1 = new Bus(71);

            // Create a second bus.
            Bus bus2 = new Bus(72);

            // Send bus1 on its way.
            bus1.Drive();

            // Wait for bus2 to warm up.
            System.Threading.Thread.Sleep(25);

            // Send bus2 on its way.
            bus2.Drive();

            // Keep the console window open in debug mode.
            System.Console.WriteLine("Press any key to exit.");
            System.Console.ReadKey();
        }
    }
    /* Sample output:
        Static constructor sets global start time to 3:57:08 PM.
        Bus #71 is created.
        Bus #72 is created.
        71 is starting its route 6.00 minutes after global start time 3:57 PM.
        72 is starting its route 31.00 minutes after global start time 3:57 PM.      
   */

Vea también

Referencia

Clases y structs (Guía de programación de C#)

Constructores (Guía de programación de C#)

Clases estáticas y sus miembros (Guía de programación de C#)

Destructores (Guía de programación de C#)

Conceptos

Guía de programación de C#