Ami*_*rma 3 c# inheritance constructor initialization
请考虑以下代码.字段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();
}
}
Run Code Online (Sandbox Code Playgroud)
Eric Lippert的博客解释了这一点:
[...]初始化的只读字段总是在其初始化状态中被观察到,除非我们首先运行所有初始化器,然后运行所有构造函数体,否则我们无法做出保证.
不确定为什么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(); // !
}
}
Run Code Online (Sandbox Code Playgroud)
2.
class Base
{
public Base()
{
Go();
}
public virtual Go() {}
}
class Derived : Base
{
X x = new X();
public override void Go()
{
x.DoSomething(); // !
}
}
Run Code Online (Sandbox Code Playgroud)
此命令在C#语言规范(17.10.2)中明确说明:
[...]构造函数隐式执行由其类中声明的实例字段的变量初始化程序指定的初始化.这对应于在进入构造函数之后和直接调用直接基类构造函数之前立即执行的赋值序列.
归档时间: |
|
查看次数: |
712 次 |
最近记录: |