如何在Main()方法之前在C#中运行静态初始化方法? [英] How can I run a static initializer method in C# before the Main() method?

查看:326
本文介绍了如何在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

从文档中:


静态在创建第一个实例或引用任何静态成员之前,将自动调用构造函数来初始化类

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆