C# 父类不包含接受0个参数的构造函数
我的C# 父类不包含接受0个参数的构造函数,c#,C#,我的Game类接受两个参数,但由于某些原因,我编写的这段代码无法工作: class Game { string consoleName; int gameID; public Game(string name, int id) { this.consoleName = name; this.gameID = id; } } 这是我的孩子班 class RolePlayingGame : Game { int le
Game
类接受两个参数,但由于某些原因,我编写的这段代码无法工作:
class Game
{
string consoleName;
int gameID;
public Game(string name, int id)
{
this.consoleName = name;
this.gameID = id;
}
}
这是我的孩子班
class RolePlayingGame : Game
{
int level;
}
或者为基类提供无参数构造函数:
class Game
{
public Game(){ //You don't even need any code in this dummy constructor
}
//....
}
注意:注意,如果您了解无参数构造函数是可以的,那么您可以使用它(如第二种方法中所提供的)
或者为基类提供无参数构造函数:
class Game
{
public Game(){ //You don't even need any code in this dummy constructor
}
//....
}
注意:注意,如果您了解无参数构造函数是可以的,您可以使用它(如第二种方法中所提供的)。尝试以下方法:
class RolePlayingGame : Game {
public RolePlayingGame(string name, int id) : base(name, id){
//Code here
}
int level;
}
正如Tim S在评论中指出的,C#会自动创建类似于公共角色扮演游戏():base(){}
。由于Game
没有无参数构造函数,因此此操作失败。因此,您需要创建一个参数化构造函数。必须在子类中显式定义构造函数。尝试以下操作:
class RolePlayingGame : Game {
public RolePlayingGame(string name, int id) : base(name, id){
//Code here
}
int level;
}
正如Tim S在评论中指出的,C#会自动创建类似于
公共角色扮演游戏():base(){}
。由于Game
没有无参数构造函数,因此此操作失败。因此,您需要创建一个参数化构造函数。必须在子类中显式定义构造函数。+1,但是为了解决问题,无参数构造函数会使基类成员未初始化。:)@是的,我同意。我要补充一点。+1,但是为了解决这个问题,无参数构造函数会使基类成员未初始化。:)@是的,我同意。我要补充一点,不像(比如)Delphi,C#不会自动让子类用参数继承构造函数。您需要在子类中显式定义相同的构造函数。当您不指定任何构造函数时,C#会自动创建类似于公共角色扮演游戏():base(){}
。因为Game
没有无参数构造函数,所以这会失败。与(例如)Delphi不同,C#不会自动让子类用参数继承构造函数。您需要在子类中显式定义相同的构造函数。当您不指定任何构造函数时,C#会自动创建类似于公共角色扮演游戏():base(){}
。由于Game
没有无参数构造函数,因此此操作失败。