问题描述
下面的C#代码不能编译。
The following C# code does not compile.
public class BaseType
{
public BaseType(int bar)
{
// Do stuff with bar...
}
}
public class DerivedType : BaseType
{
private int foo;
public DerivedType() : base(foo = 0) {}
}
在调用DerivedType的基本构造出现的错误,并显示消息不能在静态情况下访问非静态字段'富'。这是什么错误信息告诉我吗? '富'不是一成不变的,也不是类,而这些都不是静态构造函数。
The error occurs on the call to DerivedType's base constructor, with the message "Cannot access non-static field 'foo' in static context." What is this error message telling me? 'foo' is not static, and neither are the classes, and these are not static constructors.
推荐答案
在这基地(富= 0)执行 DerivedType
类尚未创建又那么它不能访问的成员而言定义呢。
At the point that base(foo = 0)
executes the DerivedType
class has not been "Created" yet so it can not access the members it defines yet.
事情发生的顺序是这样的。
The order things happen is like this
- 用户来电
新DerivedType()
- 该代码调用DerivedType的
基地(富= 0)
- 该代码调用基类型的隐式
基地()
到对象()
- 在
对象
的任何字段中的内存分配,然后对象()
构造函数运行完成。 - 在
BASETYPE
分配,然后的任何字段存储基本类型(INT吧)
构造函数运行完成。 - 在
DerivedType
的任何字段的内存是分配再DerivedType()
构造函数运行完成。
- The user calls
new DerivedType()
- The code calls DerivedType's
base(foo = 0)
- The code calls BaseType's implicit
base()
toObject()
- The memory for any fields in
Object
is allocated and then theObject()
constructor is run to completion. - The memory for any fields in
BaseType
is allocated and then theBaseType(int bar)
constructor is run to completion. - The memory for any fields in
DerivedType
is allocated and then theDerivedType()
constructor is run to completion.
所以,你看你正试图在第2步分配一个值富
,但富
将不会存在,直到第6步
So you see you are attempting to assign a value to foo
at step 2, but foo
won't exist till step 6.
这篇关于什么是静态的有关基本构造函数调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!