How can I run a static constructor?

前端 未结 10 1364
面向向阳花
面向向阳花 2020-12-08 02:15

I\'d like to execute the static constructor of a class (i.e. I want to \"load\" the class) without creating an instance. How do I do that?

Bonus question: Are there

10条回答
  •  广开言路
    2020-12-08 02:31

    The other answers are excellent, but if you need to force a class constructor to run without having a reference to the type (i.e. reflection), you can use RunClassConstructor:

    Type type = ...;
    System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(type.TypeHandle);
    

提交回复
热议问题