如果我的 2 个类构造函数具有相同数量的参数,为什么基类的构造函数没有 0 个参数很重要?

  • 本文关键字:构造函数 参数 基类 如果 c# .net
  • 更新时间 :
  • 英文 :

namespace DnD
{
class Player : Creature
{
Race race;
Spell[] cantrips = new Spell[16];
public Player(Race inputRace)
{
race = inputRace;         
}
void castSpell(Spell spell)
{

}
}
class Creature
{
String name;
public int hp;
Creature(string inputName)
{
name = inputName;
}
}
}

由于某种原因,这段代码给了我一个错误,基类(生物)有一个超过0个参数的构造函数,确切的错误消息是:'Creature' does not contain a constructor that takes 0 arguments'

我在另一个帖子上看到过类似的东西,尽管基类的构造函数有1个参数,派生类的参数为0,但在这种情况下,它们都有1。

这段代码也来自我的项目,我试图在c#中有所作为。

您只需要使用:base (someString)调用基类构造函数。这里没有显示Race类,但是如果它有string RaceName属性,您可以将其传递给基类构造函数。

public Player(Race inputRace)
: base (inputRace.RaceName)
{
race = inputRace;         
}

还要考虑Creature类是否应该有一个具体的实例。这可能是一个很好的抽象类候选。

你忽略了一个事实,如果你不在构造函数定义后写:base(...), c#会为你写:base()(公平地说,这并不明显)

每个构造函数都必须调用基构造函数,一直到下降树的对象。如果你没有提供调用哪个构造函数的指令,c#会为你调用一个(不可见的)。如果没有这样的构造函数,c#就不能自己自动排序;你必须提供方向

如果你不提供构造函数,c#会提供一个空的不做任何事情的构造函数,这样它就可以建立一个链。如果您提供了一个,它不会提供(但它可能仍然会将您的修改为call base)

所以,如果你写:

class NoConstructor{

}

c#将其修改为:

class NoConstructor{
NoConstructor():base(){}
}

如果你写:

class ConstructorNoBase{
ConstructorNoBase(){}
}

c#将其修改为:

class ConstructorNoBase{
ConstructorNoBase():base(){}
}

如果你写:

class ConstructorWithBase{
ConstructorWithBase():base{}
}

c#不去管它


你可以达到这样的情况:

class Parent{
Parent(int arg){
}
}
class Child:Parent{
}
class Child2:Parent{
Child2(int arg){
}
}

c#将它们修改为:

class Parent{
Parent(int arg):base(){ //no problem; object has a no-arg constructor
}
}
class Child:Parent{
Child():base(){    //problem, there isn't a no-arg base constructor
}
}
class Child2:Parent{
Child2(int arg):base(){   //problem, there isn't a no-arg base constructor
}
}

特别是在第二种情况下,c#不会看到Child2然后说"哦,父节点上有int arg构造函数,子节点上有int arg构造函数,我就叫base(arg)吧"-它只是把base()放在

停止创建这个"调用不存在的东西"你要么必须:

  • 提供它正在调用的东西所以它确实存在
  • base(...)提供自己的调用,以阻止c#插入自己的调用

最新更新