我有一个简单的类,它有一个静态构造函数和一个实例构造函数。现在,当我初始化类时,静态和实例构造函数都会被调用。在应用程序域中仅引用一次静态。我可以再次调用相同的类初始化和静态构造函数初始化吗?我已经尝试过但它没有发生?在类上使用垃圾回收后,有什么方法可以在 main() 方法中再次调用静态构造函数。
代码如下:
public class Employee
{
public Employee()
{
Console.WriteLine("Instance constructor called");
}
static Employee()
{
Console.WriteLine("Static constructor called");
}
~Employee()
{
//Dispose();
}
}
现在在主要方法调用中:
static void Main(string[] args)
{
Employee emp = new Employee();
Employee emp = new Employee();
}
输出:
Static constructor called Instance constructor called Instance constructor called
现在静电没有再叫了。因为它在应用程序域中被调用一次。但是他们有什么办法可以在不卸载应用程序域的情况下再次调用它。我们可以在这里使用 GC 类吗?
谢谢。 friend
最佳答案
除非你用反射来刺激它,否则静态构造函数(或更一般地说,类型初始化器)只在每个 AppDomain 的具体类中执行一次。
请注意,对于泛型,使用不同的类型参数你会得到不同的具体类:
public class Foo<T>
{
Foo()
{
Console.WriteLine("T={0}", typeof(T));
}
public static void DummyMethod() {}
}
...
Foo<int>.DummyMethod(); // Executes static constructor first
Foo<string>.DummyMethod(); // Executes static constructor first
Foo<string>.DummyMethod(); // Type is already initialized; no more output
关于C# 静态垃圾收集器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3635590/