带有部分类的静态字段初始化顺序 [英] Static field initialization order with partial classes

查看:55
本文介绍了带有部分类的静态字段初始化顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何方法可以在部分类中强制执行静态字段初始化顺序?假设在HelloWorld1.cs中,我有:

Is there any way to force the static field initialization order in partial classes? Let's say in HelloWorld1.cs I have:

partial class HelloWorld
{
  static readonly string[] a = new[] { "Hello World" };
}

在HelloWorld2.cs中的其他地方,我有:

Elsewhere in HelloWorld2.cs I have:

partial class HelloWorld
{
  static readonly string b = a[0];
}

如果a在b之前初始化,则可以,但是,如果b在a之前初始化,则抛出an.健康的方法可能是使用静态构造函数,但我很好奇,当字段类位于相同局部类的不同文件中时,是否存在一种强制或预测初始化顺序的方法.

If a is initialized before b this is fine but if b is initialized before a then it throws an. The healthy way is probably to use a static constructor but I'm curious if there's a way to force or predict the initialization order when the fields classes are in different files of the same partial class.

推荐答案

当字段存在于同一文件中时,文本顺序定义其初始化的执行:

When the fields are present in the same file, the textual order defines the execution of their initialization:

10.5.5.1变量初始化程序-静态字段初始化

类的静态字段变量初始值设定项对应于以文本顺序执行的一系列分配,这些分配以它们在类声明中的出现顺序出现.如果类中存在静态构造函数(第10.12节),则在执行该静态构造函数之前立即执行静态字段初始化程序.否则,将在首次使用该类的静态字段之前,在与实现相关的时间执行静态字段初始化程序.

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.

但是,对于在部分类的不同文件中声明的字段,顺序是不确定的:

However, in the case of fields declared in different files of partial classes, the order is undefined:

10.2.6部分类型-成员

类型中成员的顺序对于C#代码很少有重要意义,但是在与其他语言和环境进行交互时可能很重要.在这种情况下,在多个部分中声明的类型内的成员顺序是不确定的.

The ordering of members within a type is rarely significant to C# code, but may be significant when interfacing with other languages and environments. In these cases, the ordering of members within a type declared in multiple parts is undefined.

C#语言规范中.

这篇关于带有部分类的静态字段初始化顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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