什么是静态的有关基本构造函数调用? [英] What is static about a base constructor call?

查看:115
本文介绍了什么是静态的有关基本构造函数调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的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.

推荐答案

在这<点code>基地(富= 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


  1. 用户来电新DerivedType()

  2. 该代码调用DerivedType的基地(富= 0)

  3. 该代码调用基类型的隐式基地()对象()

  4. 对象的任何字段中的内存分配,然后对象()构造函数运行完成。

  5. BASETYPE 分配,然后的任何字段存储基本类型(INT吧)构造函数运行完成。

  6. DerivedType 的任何字段的内存是分配再 DerivedType()构造函数运行完成。

  1. The user calls new DerivedType()
  2. The code calls DerivedType's base(foo = 0)
  3. The code calls BaseType's implicit base() to Object()
  4. The memory for any fields in Object is allocated and then the Object() constructor is run to completion.
  5. The memory for any fields in BaseType is allocated and then the BaseType(int bar) constructor is run to completion.
  6. The memory for any fields in DerivedType is allocated and then the DerivedType() 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.

这篇关于什么是静态的有关基本构造函数调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆