Dra*_*ake 3 c# compiler-errors
以下C#代码无法编译.
public class BaseType
{
public BaseType(int bar)
{
// Do stuff with bar...
}
}
public class DerivedType : BaseType
{
private int foo;
public DerivedType() : base(foo = 0) {}
}
Run Code Online (Sandbox Code Playgroud)
在调用DerivedType的基本构造函数时发生错误,并在静态上下文中显示消息"无法访问非静态字段'foo'." 这个错误消息告诉我什么?'foo'不是静态的,也不是类,而且这些不是静态构造函数.
在base(foo = 0)执行DerivedType类的时候还没有"创建",所以它无法访问它定义的成员.
事情发生的顺序是这样的
new DerivedType()base(foo = 0)base()到Object()Object分配任何字段的内存,然后Object()构造函数运行完成.BaseType分配任何字段的内存,然后BaseType(int bar)构造函数运行完成.DerivedType分配任何字段的内存,然后DerivedType()构造函数运行完成.所以你看到你试图foo在步骤2中分配一个值,但foo在步骤6之前不会存在.