请考虑以下代码.字段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.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。