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

请考虑以下代码.字段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.

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...