gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:11:13 24 4
gpt4 key购买 nike

考虑下面的代码。字段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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com