我有一个基类:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试添加扩展此类的类时,我收到错误:
public class Derived : Base {
public Base derived = new Derived ("Foo", 0f, 0f);
}
Run Code Online (Sandbox Code Playgroud)
收到的错误说明如下: Base does not contain a constructor that takes 0 arguments
我在Derived类的第1行得到了这个错误.任何修复/原因导致这种情况发生?
如果没有在派生类中定义构造函数,则默认为无参数构造函数.基类没有,因此派生类无法实例化其基类(因此,本身).
在派生类中定义一个使用基类构造函数的构造函数:
public Derived(string foo, float bar, float foobar) : base(foo, bar, foobar) { }
Run Code Online (Sandbox Code Playgroud)
这只是一个传递构造函数.如果需要,您也可以使用无参数的,但是您仍然需要使用带有某些值的基类'构造函数.例如:
public Derived() : base("foo", 1.0, 2.0) { }
Run Code Online (Sandbox Code Playgroud)
它是一个普通的构造函数,可以包含任何你喜欢的逻辑,但它需要使用一些值来调用基类的唯一构造函数.
注:这意味着你可能不需要这个在所有:
public Base derived = new Derived ("Foo", 0f, 0f);
Run Code Online (Sandbox Code Playgroud)
看起来你正在尝试创建Base一个成员的实例Derived.但是Derived 是一个例子Base.如果你想用作Base那样的实例那么你就不想使用继承:
public class Derived { // not inheriting from Base
public Base base = new Base ("Foo", 0f, 0f);
}
Run Code Online (Sandbox Code Playgroud)
当然,在这一点上,"base"和"derived"会产生误导性的名称,因为这些类实际上并不属于继承结构.
| 归档时间: |
|
| 查看次数: |
67 次 |
| 最近记录: |