派生的 C# 错误 class

C# Error from derived class

我有一个基地class:

public class Base {
  public string Foo { get; set; }
  public float Bar { get; set; }
  public float Foobar { get; set; }

  public Base (string foo, float bar, float foobar) {
      Foo = foo;
      Bar = bar;
      Foobar = foobar;
  }
}

当我尝试添加一个 class 来扩展这个时出现错误:

public class Derived : Base {
    public Base derived = new Derived ("Foo", 0f, 0f);
}

收到的错误说明如下:Base does not contain a constructor that takes 0 arguments

我在 Derived class 的第 1 行收到此错误。 fixes/reasons 为什么会这样?

由于 class Base 的构造函数接受三个参数,您需要从 class 的构造函数传递这些参数的值 Derived:

public Derived(string foo, float bar, float foobar): base(foo, bar, foobar) {}

不在派生的class中定义构造函数,默认为无参构造函数。基础 class 没有,所以派生的 class 无法实例化其基础 class(因此,它本身)。

在派生的 class 中定义一个构造函数,它使用基础 class' 构造函数:

public Derived(string foo, float bar, float foobar) : base(foo, bar, foobar) { }

这只是一个传递构造函数。如果你愿意,你也可以使用一个无参数的,但你仍然需要使用带有一些值的基础 class' 构造函数。例如:

public Derived() : base("foo", 1.0, 2.0) { }

它是一个像其他任何构造函数一样的普通构造函数,可以包含您喜欢的任何逻辑,但它需要调用基础 class' 唯一具有某些值的构造函数。


注意:这意味着您可能根本不需要它:

public Base derived = new Derived ("Foo", 0f, 0f);

您似乎正在尝试创建 Base 的实例作为 Derived 成员。但是 Derived Base 的一个实例。如果你想使用 Base 作为这样的实例,那么你不会想使用继承:

public class Derived {  // not inheriting from Base
    public Base base = new Base ("Foo", 0f, 0f);
}

当然,那时 "base" 和 "derived" 会产生误导性名称,因为这些 class 实际上不会在继承结构中。

试试这个:

public class Derived : Base
{
    public Derived() 
        : base("Foo", 0f, 0f)
    {

    }

    public Base derived = new Derived();
}

您也可以使用对象初始化语法:

public Base derived = new Derived() { Foo = "Foo", Bar = 0f, Foobar = 0f };