[英]How can I run a static initializer method in C# before the Main() method?
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?
有没有更好的方法来做到这一点?
Simply do the initialization inside a static constructor for 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.
在创建第一个实例或引用任何静态成员之前,会自动调用静态构造函数来初始化类。
There are static constructors in C# that you can use.您可以使用 C# 中的静态构造函数。
public static class Foo
{
// Class members...
static Foo(){
init();
// other stuff
}
internal static init()
{
// Do some initialization...
}
}
Move your code from an internal static
method to a static
constructor , 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 Foo
class, whether it's a construction of an instance or access to a static member.这样,您就非常确定静态构造函数将在第一次提到您的
Foo
类时运行,无论是实例的构造还是对静态成员的访问。
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 RunClassConstructor
to trigger the static constructor of the class before using a class.您可以在使用类之前使用
RunClassConstructor
来触发类的静态构造函数。 This can be useful if, for instance, this class registers itself in a IOC container or something like this.例如,如果这个类在 IOC 容器或类似的东西中注册自己,这会很有用。
RuntimeHelpers.RunClassConstructor(typeof(Foo).TypeHandle);
You find the RuntimeHelpers
in the System.Runtime.CompilerServices
namespace.您可以在
System.Runtime.CompilerServices
命名空间中找到RuntimeHelpers
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.