这段代码似乎没有调用Mixed构造函数并打印y = 0
public class Mixed
{
public int x;
public static int y;
public Mixed()
{
x = 1;
y = 1;
}
}
public class Program
{
static Mixed mixed = new Mixed();
static void Main(string[] args)
{
Console.WriteLine("y = " + Mixed.y);
Console.ReadLine();
}
}
Run Code Online (Sandbox Code Playgroud)
但是,简单地将Main函数修改为如下所示会导致调用构造函数。
static void Main(string[] args)
{
Console.WriteLine("x = " + mixed.x);
Console.WriteLine("y = " + Mixed.y);
Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)
这打印:
x = 1
y = 1
Run Code Online (Sandbox Code Playgroud)
为什么简单地将此引用添加到非静态字段会导致构造函数被正确调用?创建对象不应该总是导致调用构造函数,而不管该对象稍后在程序中如何使用?
奇怪的是, …