简体   繁体   English

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

[英]Static constructor called after instance constructor?

Dear all, the question like this one has been already asked , but among the answers there was no explanation of the problem which I see. 亲爱的,这个问题已经被问过了 ,但在答案中,没有解释我所看到的问题。

The problem: the C# Programming Guide says: 问题: C#编程指南说:

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. 在创建第一个实例或引用任何静态成员之前自动调用它。

In particular, static constructor is called before any instance of a class is created. 特别是,在创建类的任何实例之前调用静态构造函数。 (This doesn't ensure that the static constructor finishes before creation of instance, but this is a different story.) (这不能确保静态构造函数在创建实例之前完成,但这是另一回事。)

Let's consider the example code: 我们来看一下示例代码:

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");
    }
}

It outputs: 它输出:

Main() started Main()开始了
new Test() 新测试()
static Test() 静态测试()
Test.test = Test Test.test =测试
Main() finished Main()完成了

So we can see that the instance constructor finishes (and thus an instance is created) before the static constructor starts . 因此,我们可以看到实例构造函数在静态构造函数启动 之前完成(因此创建了一个实例)。 Doesn't this contradict the Guide? 这不符合指南吗? Maybe the initialization of static fields is considered to be an implicit part of static constructor? 也许静态字段的初始化被认为是静态构造函数的隐式部分?

Inline initializers for static fields run before the explicit static constructor. static字段的内联初始值设定项在显式static构造函数之前运行。

The compiler transforms your class into something like this: 编译器将您的类转换为以下内容:

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

Note that this is independent of the declaration order. 请注意,这与声明顺序无关。

To quote the 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. 如果类中存在静态构造函数(第10.11节) ,则在执行该静态构造函数之前立即执行静态字段初始值设定项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM