gpt4 book ai didi

c# - 为什么不调用此 C# 实例构造函数,除非存在对非静态成员的引用?

转载 作者:行者123 更新时间:2023-11-30 12:20:21 25 4
gpt4 key购买 nike

<分区>

此代码似乎没有调用 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();
}
}

但是,只需将 Main 函数修改为如下所示,就会调用构造函数。

static void Main(string[] args)
{
Console.WriteLine("x = " + mixed.x);
Console.WriteLine("y = " + Mixed.y);

Console.ReadLine();
}

这打印:

x = 1
y = 1

为什么简单地将此引用添加到非静态字段会导致构造函数被正确调用?创建对象不应该总是导致构造函数被调用,而不管该对象稍后在程序中如何使用吗?

奇怪的是,像这样使 Mixed 对象成为非静态对象也会导致调用构造函数:

public class Program
{
static void Main(string[] args)
{
Mixed mixed = new Mixed();

Console.WriteLine("y = " + Mixed.y);

Console.ReadLine();
}
}

然而,这对我来说似乎也没有意义。将 Mixed 对象声明为 static 只意味着内存中只有该对象的一个​​副本,而不管 Program 被实例化了多少次。这是某种编译器优化,对于静态字段,编译器在实际实例化之前等待对该类型的非静态字段的引用吗?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com