gpt4 book ai didi

c# - 静态字段什么时候出现?

转载 作者:太空狗 更新时间:2023-10-29 22:17:24 29 4
gpt4 key购买 nike

我试图了解确切的静态字段何时出现并一直在阅读这篇 MSDN 文章 - http://msdn.microsoft.com/en-us/library/79b3xss3 - 但它似乎自相矛盾:

首先它说:

静态成员在第一次访问静态成员之前和静态构造函数(如果有的话)被调用之前初始化。

然后它接着说:

如果您的类包含静态字段,请提供一个静态构造函数,在类加载时初始化它们。

所以,我的问题基本上是这样的:静态字段何时实际初始化以及它们何时首次存在?是在调用静态构造函数之前、期间还是之后?

非常感谢!

最佳答案

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

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

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

正如您从规范中看到的那样,它们出现的实际“时间”是特定于实现的,并且可能会发生变化。唯一的保证是它们将在调用静态构造函数之前存在,这将始终在它们在代码中使用之前发生。该规范声明(在 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.

关于c# - 静态字段什么时候出现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4995670/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com