在实例构造函数之后调用静态构造函数? [英] Static constructor called after instance constructor?

查看:34
本文介绍了在实例构造函数之后调用静态构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的,像这样的问题一直已经问过,但在答案中没有我看到的问题的解释.

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.

问题: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.)

让我们考虑示例代码:

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() 开始
新测试()
静态测试()
测试.测试 = 测试
Main() 完成

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

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

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?

推荐答案

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

Inline initializers for static fields run before the explicit static constructor.

编译器将你的类转换成这样:

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.

引用规范:

静态字段变量初始化器一个类对应于一个序列中执行的任务它们出现的文本顺序类声明.如果一个静态构造函数 (第 10.11 节) 存在于类,静态的执行字段初始值设定项立即发生在执行该静态之前构造函数.

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.

这篇关于在实例构造函数之后调用静态构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆