c# - 为什么子类变量先于父类成员变量初始化

标签 c# inheritance constructor initialization

考虑下面的代码。字段ijmn 之前初始化。我们知道父对象是在子对象之前创建的,但是在我的程序中,编译器在基类之前为子类的成员变量分配和初始化内存。这是为什么?

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.

关于c# - 为什么子类变量先于父类成员变量初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20850323/

相关文章:

C# 比较两个 double 与 .Equals()

c# - 在不影响相邻列的情况下调整 DataGridView 列的大小?

c++ - 从 friend 类继承时无法使用大括号括起来的初始值设定项列表

javascript - 在 JavaScript 中使用对象字面量实现继承

c++ - 如何通过构造函数将容量大小传递给无锁 spsc_queue

c# - 用 C# 编写脚本 - XNA 和 360 的可移植库?

c# - 我如何从 C# 中的选定内容中排序

c++ - 是否可以在派生类中使用复制构造函数而不使用基复制构造函数?

javascript - 构造函数可以返回原语吗?

c++ - 在 C++ 中创建一个类