如何在C#中的静态字段初始化工作? [英] How does static field initialization work in C#?

查看:254
本文介绍了如何在C#中的静态字段初始化工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果静态字段初始化时调用构造函数之前完成?



下面的程序提供了看起来不正确对我的输出。

 新A()
_A == NULL
静态A()
新A()
_A一个==

中的代码:

 大众A级
{
公共静态字符串_A =(新A())I()。

公开发行A()
{
Console.WriteLine(新A());
如果(_A == NULL)
Console.WriteLine(_ A ==空);
,否则
Console.WriteLine(_ A ==+ _A);
}

静态A()
{
Console.WriteLine(静态A());
}

公共字符串我()
{
返回A;
}
}

类节目
{
静态无效的主要(字串[] args)
{
VAR一个=新的A();
}
}


解决方案

这是正确的。



您静态初始化,那么静态构造函数是标准的构造函数之前运行,但是当它运行时,它使用新的A(),所以通过你的非-static构造路径。这将导致您看到的消息



下面是执行的完整路径:



当您第一次调用 VAR一个=新的A(); 在你的程序中,这是第一次访问



这意志。火了 A._A



在这一点上的静态初始化,A._A构造与 _A =(新A())I();



这打

  
Console.WriteLine(新A());
如果(_A == NULL)
Console.WriteLine(_ A ==空);



,因为在这一点上,_A尚未设置用返回,构造类型(尚未)。



接下来,静态构造函数 A {静态A(); } 运行。

最后,你原来的语句( VAR一个=新的A() $ 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

The code:

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();
    }
}

解决方案

This is correct.

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:

When you first call var a = new A(); in your program, this is the first time A is accessed.

This will fire off the static initialization of A._A

At this point, A._A constructs with _A = (new A()).I();

This hits


Console.WriteLine("new A()");
if (_A == null)
    Console.WriteLine("_A == null");        

since at this point, _A hasn't been set with the returned, constructed type (yet).

Next, the static constructor A { static A(); } is run. This prints the "static A()" message.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆