本文介绍了如何在Main()方法之前在C#中运行静态初始化方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用初始化方法给静态类:

Given a static class with an initializer method:

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

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

如何确保初始化程序在 Main()之前运行?

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

我能想到的最好的方法是将其添加到 Foo

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?

推荐答案

只需在,用于 Foo

从文档中:

这篇关于如何在Main()方法之前在C#中运行静态初始化方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 02:08
查看更多