gpt4 book ai didi

c# - 静态字段初始化在 C# 中如何工作?

转载 作者:IT王子 更新时间:2023-10-29 04:24:39 24 4
gpt4 key购买 nike

是否应该在调用构造函数之前完成静态字段初始化?

以下程序提供的输出对我来说似乎不正确。

new A()
_A == null
static A()
new A()
_A == A

代码:

public class A
{
public static string _A = (new A()).I();

public A()
{
Console.WriteLine("new A()");
if (_A == null)
Console.WriteLine("_A == null");
else
Console.WriteLine("_A == " + _A);
}

static A()
{
Console.WriteLine("static A()");
}

public string I()
{
return "A";
}
}

class Program
{
static void Main(string[] args)
{
var a = new A();
}
}

最佳答案

这是正确的。

你的静态初始化器,然后静态构造函数在你的标准构造函数之前运行,但当它运行时,它使用新的 A(),所以通过你的非静态构造函数路径。这会导致您看到消息。

这里是完整的执行路径:

当您在程序中第一次调用 var a = new A(); 时,这是第一次访问 A。

这将触发 A._A 的静态初始化

此时,A._A 构造为 _A = (new A()).I();

这个命中


Console.WriteLine("new A()");
if (_A == null)
Console.WriteLine("_A == null");

因为此时,_A 尚未设置为返回的构造类型(还)。

接下来,静态构造器 A { static A(); } 运行。这将打印“static A()”消息。

最后,您的原始语句 (var a = new A();) 被执行,但此时,静态构造已构建,因此您得到了最终打印。

关于c# - 静态字段初始化在 C# 中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/710793/

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