gpt4 book ai didi

c# - 在实例构造函数之后调用静态构造函数?

转载 作者:可可西里 更新时间:2023-11-01 02:59:22 25 4
gpt4 key购买 nike

亲爱的,像这样的问题已经already asked , 但在答案中没有对我看到的问题的解释。

问题:C# Programming Guide说:

A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.

特别是,在创建类的任何实例之前调用静态构造函数。 (这不能确保静态构造函数在创建实例之前完成,但这是另一回事。)

让我们考虑示例代码:

using System;

public class Test
{
static public Test test = new Test();
static Test()
{
Console.WriteLine("static Test()");
}
public Test()
{
Console.WriteLine("new Test()");
}
}

public class Program
{
public static void Main()
{
Console.WriteLine("Main() started");
Console.WriteLine("Test.test = " + Test.test);
Console.WriteLine("Main() finished");
}
}

输出:

Main() started
new Test()
static Test()
Test.test = Test
Main() finished

因此我们可以看到实例构造函数静态构造函数开始之前完成(因此创建了一个实例)。这不是与指南相矛盾吗?也许静态字段的初始化被认为是静态构造函数的隐式部分?

最佳答案

static 字段的内联初始化器在显式 static 构造函数之前运行。

编译器将您的类转换为如下内容:

public class Test {
.cctor { //Class constructor
Test.test = new Test(); //Inline field initializer
Console.WriteLine("static Test()"); //Explicit static ctor
}
.ctor { ... } //Instance constructor
}

请注意,这与声明顺序无关。

引用 spec :

The static field variable initializers of a class correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration. If a static constructor (Section 10.11) exists in the class, execution of the static field initializers occurs immediately prior to executing that static constructor.

关于c# - 在实例构造函数之后调用静态构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4150151/

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