如何在 Main() 方法之前在 C# 中运行静态初始化方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13622754/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I run a static initializer method in C# before the Main() method?
提问by Matt
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()?
如何确保初始化程序在之前运行Main()?
The best I can think of is to add this to Foo:
我能想到的最好的方法是将其添加到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?
这会起作用还是有一些不可预见的警告?有没有更好的方法来做到这一点?
采纳答案by Jon
Simply do the initialization inside a static constructorfor Foo.
简单地做一个内部的初始化静态构造函数的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.
在创建第一个实例或引用任何静态成员之前,会自动调用静态构造函数来初始化类。
回答by SWeko
Move your code from an internal staticmethod to a staticconstructor, like this:
将您的代码从internal static方法移动到static构造函数,如下所示:
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 Fooclass, whether it's a construction of an instance or access to a static member.
这样,您就非常确定静态构造函数将在第一次提到您的Foo类时运行,无论是实例的构造还是对静态成员的访问。
回答by Jo?o Sim?es
There are static constructorsin C# that you can use.
您可以使用 C#中的静态构造函数。
public static class Foo
{
// Class members...
static Foo(){
init();
// other stuff
}
internal static init()
{
// Do some initialization...
}
}
回答by Olivier Jacot-Descombes
Place your initialization code in the static constructor of the class
将初始化代码放在类的静态构造函数中
static Foo()
{
// Initialization code
}
This constructor is run the first time the class is accessed.
这个构造函数在第一次访问类时运行。
You can use RunClassConstructorto trigger the static constructor of the class before using a class. This can be useful if, for instance, this class registers itself in a IOC container or something like this.
您可以RunClassConstructor在使用类之前使用来触发类的静态构造函数。例如,如果这个类在 IOC 容器或类似的东西中注册自己,这会很有用。
RuntimeHelpers.RunClassConstructor(typeof(Foo).TypeHandle);
You find the RuntimeHelpersin the System.Runtime.CompilerServicesnamespace.
您可以RuntimeHelpers在System.Runtime.CompilerServices命名空间中找到。

