How does static field initialization work in C#?(静态字段初始化如何在 C# 中工作?)
问题描述
是否应该在调用构造函数之前完成静态字段初始化?
Should static field initialization be completed before constructor is called?
以下程序提供的输出对我来说似乎不正确.
The following program provides output that seems incorrect to me.
new A()
_A == null
static A()
new A()
_A == A
代码:
public class A
{
public static string _A = (new A()).I();
public A()
{
Console.WriteLine("new A()");
if (_A == null)
Console.WriteLine("_A == null");
else
Console.WriteLine("_A == " + _A);
}
static A()
{
Console.WriteLine("static A()");
}
public string I()
{
return "A";
}
}
class Program
{
static void Main(string[] args)
{
var a = new A();
}
}
推荐答案
这是正确的.
你的静态初始化器,然后静态构造器在你的标准构造器之前运行,但是当它运行时,它使用 new A(),所以通过你的非静态构造器路径.这会导致您看到的消息.
Your static initializers, then the static constructor is run before your standard constructor, but when it runs, it's using new A(), so passing through your non-static constructor path. This causes the messages you see.
这里是完整的执行路径:
Here is the full path of execution:
当您在程序中第一次调用 var a = new A();
时,这是第一次访问 A.
When you first call var a = new A();
in your program, this is the first time A is accessed.
这将触发 A._A
此时,A._A 构造为 _A = (new A()).I();
At this point, A._A constructs with _A = (new A()).I();
这击中了
Console.WriteLine("new A()");
if (_A == null)
Console.WriteLine("_A == null");
从此时起,_A 尚未设置为返回的构造类型.
since at this point, _A hasn't been set with the returned, constructed type (yet).
接下来,静态构造函数 A { static A();}
运行.这将打印静态 A()"消息.
Next, the static constructor A { static A(); }
is run. This prints the "static A()" message.
最后,您的原始语句 (var a = new A();
) 被执行,但此时,静态已构建,因此您得到最终打印.
Finally, your original statement (var a = new A();
) is executed, but at this point, the statics are constructed, so you get the final print.
这篇关于静态字段初始化如何在 C# 中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:静态字段初始化如何在 C# 中工作?
基础教程推荐
- SSE 浮点算术是否可重现? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 如何激活MC67中的红灯 2022-01-01