加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 为什么子类变量在父类成员变量之前初始化

发布时间:2020-12-16 01:59:15 所属栏目:百科 来源:网络整理
导读:请考虑以下代码.字段i和j在m和n之前初始化.我们知道父对象是在子对象之前创建的,但是在我的程序中,编译器正在为基类之前的子类的成员变量分配和初始化内存.这是为什么? class X{ private int m = 0; private int n = 90; public X() { }}class Y:X{ private
请考虑以下代码.字段i和j在m和n之前初始化.我们知道父对象是在子对象之前创建的,但是在我的程序中,编译器正在为基类之前的子类的成员变量分配和初始化内存.这是为什么?

class X
{
    private int m = 0;
    private int n = 90;
    public X() { }
}

class Y:X
{
    private int i = 8;
    private int j = 6;
    public Y()
    { }
    public static void Main(string []args)
    {
        Y y1 = new Y();  
    }
}

解决方法

这在 Eric Lippert’s blog中解释:

[…] an initialized readonly field is always observed in its initialized state,and we cannot make that guarantee unless we run all the initializers first,and then all of the constructor bodies.

不确定为什么readonly在这里提到,但是例如,这确保了以下场景,尽管是愚蠢的,工作:

1.

class Base
{
    public Base()
    {
        if (this is Derived) (this as Derived).Go();
    }
}

class Derived : Base
{
    X x = new X();

    public void Go()
    {
        x.DoSomething(); // !
    }
}

2.

class Base
{
    public Base()
    {
        Go();
    }

    public virtual Go() {}
}

class Derived : Base
{
    X x = new X();

    public override void Go()
    {
        x.DoSomething(); // !
    }
}

该命令在C# Language Specification(17.10.2)中明确说明:

[…] constructor implicitly performs the initializations specified by the variable-initializers of the instance fields declared in its class. This corresponds to a sequence of assignments that are executed immediately upon entry to the constructor and before the implicit invocation of the direct base class constructor.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读