我有一个基类:
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;
}
}
当我尝试添加扩展此类的类时,我收到错误:
public class Derived : Base {
public Base derived = new Derived ("Foo", 0f, 0f);
}
收到的错误说明了以下内容:Base does not contain a constructor that takes 0 arguments
我在Derived类的第1行遇到此错误。 发生这种情况的任何修复/原因?
答案 0 :(得分:8)
如果没有在派生类中定义构造函数,则默认为无参数构造函数。基类没有的,因此派生类无法实例化其基类(因此本身)。
在派生类中定义一个使用基类的构造函数'构造:
public Derived(string foo, float bar, float foobar) : base(foo, bar, foobar) { }
这只是一个传递构造函数。如果你愿意,你也可以使用无参数的,但你仍然需要使用基类'具有一些值的构造函数。例如:
public Derived() : base("foo", 1.0, 2.0) { }
它是一个普通的构造函数,可以包含任何你喜欢的逻辑,但它需要调用基类'只有具有一些值的构造函数。
注意:这意味着可能根本不需要这样:
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);
}
当然,那时候"基地"和"派生"会产生误导性的名称,因为这些类实际上并不属于继承结构。
答案 1 :(得分:4)
由于类Base
的构造函数接受三个参数,因此需要从类Derived
的构造函数中传递这些参数的值:
public Derived(string foo, float bar, float foobar): base(foo, bar, foobar) {}
答案 2 :(得分:0)
试试这个:
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 };