How can I run a static initializer method in C# be

2019-01-27 13:46发布

Given a static class with an initializer method:

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

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

How can I ensure the initializer is run before Main()?

The best I can think of is to add this to Foo:

    private class Initializer
    {
        private static bool isDone = false;
        public Initializer()
        {
            if (!isDone)
            {
                init();
                isDone = true;
            }
        }
    }
    private static readonly Initializer initializer = new Initializer();

Will this work or are there some unforeseen caveats? And is there any better way of doing this?

3条回答
贼婆χ
2楼-- · 2019-01-27 14:19

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.

查看更多
Luminary・发光体
3楼-- · 2019-01-27 14:29

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...
    }
}
查看更多
Explosion°爆炸
4楼-- · 2019-01-27 14:33

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.

查看更多
登录 后发表回答