我遇到了一个我想了解的 C# 行为。
为什么在这两种情况下实例构造函数都先运行?
class Program
{
public static void Main()
{
//Singleton s = new Singleton(); case 1
var test = Singleton.Instance; // case 2
}
}
class Singleton
{
static readonly Singleton _instance = new Singleton();
public static Singleton Instance { get { return _instance; } }
private Singleton()
{
Console.WriteLine("Instance Constructor");
}
static Singleton()
{
Console.WriteLine("Static Constructor");
}
}
输出:
Instance Constructor
Static Constructor
最佳答案
它不会先运行,只是看起来好像会运行。你写的(大致)等同于
class Singleton
{
static readonly Singleton _instance;
public static Singleton Instance { get { return _instance; } }
private Singleton()
{
Console.WriteLine("Instance Constructor");
}
static Singleton()
{
_instance = new Singleton();
Console.WriteLine("Static Constructor");
}
}
也就是说,实例构造函数被调用,静态构造函数正在执行。
字段初始化在静态构造函数中首先发生(在您的 Console.WriteLine
调用之前)的原因很简单:静态构造函数的其余部分可能依赖于那些已初始化的字段。
关于c# - 为什么实例构造函数先运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50079980/