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

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

问题描述

很抱歉,像这样的问题已经

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()开始

new Test()

static Test()

Test.test =测试

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.

如下:

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.

引用 spec


类的变量初始化器
对应于在
文本顺序中执行的
分配序列,它们出现在
类的声明中。 如果$ b $中存在静态
构造函数(第10.11节), b类,在执行静态
构造函数之前立即执行静态
字段初始化程序

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天全站免登陆