静态构造函数调用后实例构造函数?

编程入门 行业动态 更新时间:2024-10-11 19:25:47
本文介绍了静态构造函数调用后实例构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

很抱歉,像这样的问题已经

Dear all, the question like this one has been already asked, but among the answers there was no explanation of the problem which I see.

问题: C#编程指南说:

静态构造函数用于初始化任何静态数据,或执行仅需执行一次的特定操作。它会在创建第一个实例或引用任何静态成员之前自动调用。

A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.

特别地,静态构造函数在任何实例的类被创建。 (这不能确保静态构造函数在创建实例之前完成,但这是一个不同的故事。)

In particular, static constructor is called before any instance of a class is created. (This doesn't ensure that the static constructor finishes before creation of instance, but this is a different story.)

让我们考虑示例代码:

using System; public class Test { static public Test test = new Test(); static Test() { Console.WriteLine("static Test()"); } public Test() { Console.WriteLine("new Test()"); } } public class Program { public static void Main() { Console.WriteLine("Main() started"); Console.WriteLine("Test.test = " + Test.test); Console.WriteLine("Main() finished"); } }

它输出:

Main()开始 new Test() static Test() Test.test =测试 Main()完成

Main() started new Test() static Test() Test.test = Test Main() finished

所以我们可以看到实例构造函数完成 这不是与指南矛盾吗?也许静态字段的初始化被认为是静态构造函数的隐式部分?

So we can see that the instance constructor finishes (and thus an instance is created) before the static constructor starts. Doesn't this contradict the Guide? Maybe the initialization of static fields is considered to be an implicit part of static constructor?

推荐答案

static 字段在显式 static 构造函数之前运行。

Inline initializers for static fields run before the explicit static constructor.

如下:

public class Test { .cctor { //Class constructor Test.test = new Test(); //Inline field initializer Console.WriteLine("static Test()"); //Explicit static ctor } .ctor { ... } //Instance constructor }

请注意,这与声明顺序无关。

Note that this is independent of the declaration order.

引用 spec :

类的变量初始化器对应于在文本顺序中执行的分配序列,它们出现在类的声明中。 如果$ b $中存在静态构造函数(第10.11节), 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.

更多推荐

静态构造函数调用后实例构造函数?

本文发布于:2023-11-12 09:54:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581168.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   静态   实例

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!