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# 中工作?


- C#MongoDB使用Builders查找派生对象 2022-09-04
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 输入按键事件处理程序 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01