How do I invoke a static constructor with reflection?

前端 未结 4 379
我在风中等你
我在风中等你 2020-12-03 03:33

How can I get the ConstructorInfo for a static constructor?

public class MyClass
{
    public static int SomeValue;

    static MyClass()
    {
         


        
4条回答
  •  再見小時候
    2020-12-03 04:03

    Even though it is possible, it may not be a good idea to do that. However, if you access any member of the class, the runtime will invoke the static constructor automatically for you. For example:

    // Read the field 'SomeValue', so that the runtime invokes static ctor   
    Type myClass = typeof(MyClass);
    myClass.GetField("SomeValue").GetValue(null);
    

    Since accessing a field of the class cannot cause any side-effect (other than initialization of the class and call to the static constructor), this should be a relatively safe way to do this in general (however, it will stil work only for classes with some static field). This has the benefit that it guarantees that the type constructor will be invoked at most once which is quite important.

提交回复
热议问题