在静态类静态字段顺序初始化 [英] Initialization Order of Static Fields in Static Class

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

问题描述

给出下面的代码:

public static class Helpers
{
   private static Char[] myChars = new Char[] {'a', 'b'};

   private static Int32 myCharsSize = myChars.Length;
}



能够保证所有的 myChars 将被初始化<前>我用它的长度分配为 myCharsSize

推荐答案

是的,他们会,请参阅 10.4.5.1静态字段初始化

Yes, they will, please see 10.4.5.1 Static field initialization:

一类的静态字段变量初始
分别对应于
赋值序列在它们出现在
类声明的
文本顺序执行。
如果静态
构造函数(第10.11节)存在于
类,静态
字段初始化的执行时立即
执行静态
构造之前。否则,静态
字段初始正以
实现相关的时间$之前执行B $ 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. Otherwise, the static field initializers are executed at an implementation-dependent time prior to the first use of a static field of that class.

话虽这么说,我认为这将是更好的做一个静态类型初始化(静态构造函数)内初始化。

That being said I think it would be better to do the initialization inside a static type initializer (static constructor).

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

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