How can I run a static initializer method in C# before the Main() method?

白昼怎懂夜的黑 提交于 2019-11-29 13:10:12

Simply do the initialization inside a static constructor for Foo.

From the documentation:

A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.

There are static constructors in C# that you can use.

public static class Foo
{
    // Class members...

    static Foo(){
        init();
        // other stuff
    }

    internal static init()
    {
        // Do some initialization...
    }
}

Move your code from an internal static method to a static constructor like this:

public static class Foo
{
  // Class members...

  static Foo()
  {
    // Do some initialization...
  }
}

This way you are quite sure that the static constructor will be run on first mention of your Foo class, whether is a construction of an instance or access to a static member.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!