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

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

问题描述

以下代码:

static void Main(string[] args){Console.WriteLine("0");字符串 h = Foo.X;Console.WriteLine("2");}公共静态类 Foo{公共静态字符串 X = ((Func)delegate(string g){Console.WriteLine(g);返回 (g);})("_aaa");静态 Foo(){Console.WriteLine("ctor");}}

将打印:

<预><代码>0_aaa演员2

我了解 beforefieldinit 行为(有/没有静态构造函数等).

理解的是为什么ctor(在输出中)是after _aaa?

没有任何意义,如果我想在构造函数中初始化变量怎么办?

问题

为什么X的初始化在ctor之前?

解决方案

ctor 在字段初始值设定项之后的原因是因为这是指定的方式.来自 C# 规范(重点是我的):

<块引用>

10.5.5.1 静态字段初始化类的静态字段变量初始化器对应于一系列赋值按照它们在类中出现的文本顺序执行宣言.如果类中存在静态构造函数(第 10.12 节),静态字段初始值设定项的执行发生在紧接在执行那个静态构造函数.否则,静态字段初始化器在依赖于实现的时间执行第一次使用该类的静态字段

如果您想完全控制初始化顺序,请将其全部移到构造函数中.

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

Will print:

0
_aaa
ctor
2

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

The thing which I don't understand is why the ctor (in the output) is after _aaa?

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

Question

Why does the initialization of X is before the ctor?

解决方案

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