静态字段初始化如何在 C# 中工作?

How does static field initialization work in C#?(静态字段初始化如何在 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# 中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)