[英]Parent class does not contain a constructor that takes 0 arguments
My Game
class takes two arguments, but for some reason this code I wrote won't work: 我的
Game
类有两个参数,但是由于某种原因,我编写的这段代码不起作用:
class Game
{
string consoleName;
int gameID;
public Game(string name, int id)
{
this.consoleName = name;
this.gameID = id;
}
}
Here is my child class. 这是我的孩子班。
class RolePlayingGame : Game
{
int level;
}
class RolePlayingGame : Game {
public RolePlayingGame(string name, int id) : base(name, id){
//...
}
int level;
}
Or provide a parameterless constructor for your base class: 或为您的基类提供无参数的构造函数:
class Game
{
public Game(){ //You don't even need any code in this dummy constructor
}
//....
}
NOTE : Note that if you understand a parameterless constructor is OK, you can use it (as provided in the second approach). 注意 :请注意,如果您了解无参数构造函数是可以的,则可以使用它(第二种方法中提供)。
Try this: 尝试这个:
class RolePlayingGame : Game {
public RolePlayingGame(string name, int id) : base(name, id){
//Code here
}
int level;
}
As noted by Tim S in comments, C# automatically creates something like a public RolePlayingGame() : base() { }
. 正如Tim S在评论中指出的那样,C#自动创建类似于
public RolePlayingGame() : base() { }
。 Since Game
does not have a parameterless constructor, this fails. 由于
Game
没有无参数的构造函数,因此会失败。 So you need to create a parameterized constructor. 因此,您需要创建一个参数化的构造函数。 You have to explicitly define the constructors in the sub classes.
您必须在子类中显式定义构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.