Pregunta

¿Hay una manera en C # o .NET IL para forzar una clase que tiene un inicializador de tipo (constructor estático) para cargar sí mismo, sin acceder a cualquiera de sus parámetros?

Suponiendo que tengo la clase

public static class LogInitialization {
    static LogInitialization() {
        System.Console.WriteLine("Initialized");
    }
}

¿Hay una manera de conseguir esta línea para imprimir?

Tenga en cuenta que la clase es estática por lo que no puede crear una instancia que a fuerza de inicialización, y no tiene miembros públicos de modo que no puedan acceder a ellos para iniciarlo.

¿Fue útil?

Solución

Rummaging in the CLI spec, I found a reference to the method RuntimeHelpers.RunClassConstructor

If a language wishes to provide more rigid behavior — e.g., type initialization automatically triggers execution of base class’s initializers, in a top-to-bottom order — then it can do so by either:

  • defining hidden static fields and code in each class constructor that touches the hidden static field of its base class and/or interfaces it implements, or
  • by making explicit calls to System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor (see Partition IV).

Otros consejos

I usually create a dummy (empty) Init method on classes with static constructors to force the static constructor execution. ie.

public static void Initialize() 
{ 
  // this will force your static constructor to execute, obviously
}

That said, you can always go for the Type.TypeInitializer with reflection... http://msdn.microsoft.com/en-us/library/system.type.typeinitializer.aspx

EDIT: One other thing I've done in the past, is to create an attribute called RequiresInitializationAttribute then on AssemblyLoad scan the assembly for types with such an attribute and using the type.TypeInitializer to force the static constructor to execute when the containing assembly is loaded.

I guess the real question, as usual, is...what are you trying to accomplish?

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top