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

编程入门 行业动态 更新时间:2024-10-10 17:22:29
本文介绍了静态字段初始化如何在 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# 中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-03-19 00:03:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/625735.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   初始化   静态   如何在   工作

发布评论

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

>www.elefans.com

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