How can I run a static constructor?

前端 未结 10 1365
面向向阳花
面向向阳花 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:52

    Just reference one of your static fields. This will force your static initialization code to run. For example:

    public class MyClass
    {
        private static readonly int someStaticField;
    
        static MyClass() => someStaticField = 1;
    
        // any no-op method call accepting your object will do fine
        public static void TouchMe() => GC.KeepAlive(someStaticField);
    }
    

    Usage:

    // initialize statics
    MyClass.TouchMe();
    

提交回复
热议问题