为什么静态字段初始化静态构造函数之前发生? [英] Why static fields initialization occurs before the static constructor?

查看:167
本文介绍了为什么静态字段初始化静态构造函数之前发生?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面code:

static void Main(string[] args)
{
    Console.WriteLine("0");
    string h = Foo.X;
    Console.WriteLine("2");
}

public static class Foo
{
    public static string X = ((Func<string, string>)delegate(string g)
    {
        Console.WriteLine(g);
        return (g);
    })("_aaa");

    static Foo()
    {
        Console.WriteLine("ctor");
    }
}

将会打印:

0
_aaa
ctor
2

我知道所有关于 beforefieldinit 行为(与输入/输出静态构造函数等)。

I know all about the beforefieldinit behavior (with/out static constructor etc.).

我的事不要不解的是,为什么男星 类似_aaa

The thing which I don't understand is why the ctor is after _aaa?

它没有任何意义,如果我要初始化在构造函数中的变量?

It doesn't make any sense, what if i want to initialize variables in the constructor?

为什么 X 的初始化前的男星

推荐答案

究其原因男星是后场的初始化是因为这是它被指定的方式。从C#规范(重点是我的):

The reason ctor is after the field initializers is because that's the way it is specified. From the C# specification (emphasis is mine):

10.5.5.1静态字段初始化类的静态字段变量初始对应任务的序列   在它们出现在类的文字顺序执行   宣言。 如果一个静态构造函数(§10.12)存在于类,   执行静态字段初始发生前夕   执行静态构造函数。,否则,静电场   初始化是在实现有关的时间之前执行   第一次使用静态字段的该类的

10.5.5.1 Static field initialization 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 (§10.12) exists in the class, execution of the static field initializers occurs immediately prior to executing that static constructor. Otherwise, the static field initializers are executed at an implementation-dependent time prior to the first use of a static field of that class

如果您希望您的初始订单的总量控制,将它所有的构造函数中。

If you want to have total control of your initialization order, move it all inside the constructor.

这篇关于为什么静态字段初始化静态构造函数之前发生?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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