Forcing class load

前端 未结 2 656
清歌不尽
清歌不尽 2021-02-13 21:36

Is there a way in C# or .net IL to force a class that has a type initializer (static constructor) to load itself, without accessing any of its parameters?

Assuming I\'ve

2条回答
  •  旧时难觅i
    2021-02-13 22:17

    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?

提交回复
热议问题