Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
979 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...