静电场何时出现? [英] When do static fields come into existence?

查看:47
本文介绍了静电场何时出现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解何时确切存在静态字段,并且正在阅读此MSDN文章-

I'm trying to understand when exactly static fields come into existence and have been reading this MSDN article - http://msdn.microsoft.com/en-us/library/79b3xss3 - but it seems to contradict itself:

首先它说:

静态成员在首次访问静态成员之前以及在调用静态构造函数(如果有的话)之前被初始化.

Static members are initialized before the static member is accessed for the first time and before the static constructor, if there is one, is called.

但是接着说:

如果您的类包含静态字段,请提供一个静态构造函数,该静态构造函数在加载类时对其进行初始化.

If your class contains static fields, provide a static constructor that initializes them when the class is loaded.

所以,我的问题基本上是这样的:静态字段何时真正初始化,何时首次出现?是在调用静态构造函数之前,期间还是之后?

So, my question is basically this: When are static fields actually initialized and when do they first come into existence? Is it before the static constructor is called, during, or after?

非常感谢!

推荐答案

C#语言规范规定(在 10.5.5.1静态字段初始化中):

The C# Language specification states (in 10.5.5.1 Static field initialization):

类的静态字段变量初始值设定项对应于按其在类声明中出现的文本顺序执行的分配序列.如果类中存在静态构造函数(第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

我相信第二行中的指导实际上是使用字段初始化程序初始化未内联完成的静态字段.在这种情况下,您应该使用静态构造函数来保证它们将在使用前进行初始化.

I believe the guidance in your second line is actually to initialize static fields that are not done inline, using field initializers. In that case, you should use a static constructor to guarantee that they will be initialized prior to usage.

从说明书中可以看到,实际的时间"指的是实际的时间".它们的存在是特定于实现的,并且可能会发生变化.唯一的保证是它们将在调用静态构造函数之前就存在,并且始终在它们在代码中使用之前发生.该规范规定(在10.12中):

As you can see from the specification, the actual "time" they come into existence is implementation specific, and subject to change. The only guarantee is that they will exist prior to the static constructor being called, which will always occur prior to their usage in code. This specification states (in 10.12):

在应用程序域中发生的以下第一个事件触发了静态构造函数的执行:

The execution of a static constructor is triggered by the first of the following events to occur within an application domain:

·创建了该类类型的实例.

· An instance of the class type is created.

·引用了该类类型的任何静态成员.

· Any of the static members of the class type are referenced.

这篇关于静电场何时出现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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