我有一个抽象类Animal
看起来像这样
abstract class Animal{
protected int numberOfPaws;
public abstract String speak();
public String toString(){
return "I have " + numberOfPaws + " paws";
}
}
然后我有一个派生类,其toString()
的新实现看起来像这样
class Cow : Animal{
public Cow : base(4) {}
public override String speak(){
return "Moo!";
}
public new Strinf toString(){
return "I am a Cow " + base.toString();
}
}
我有一个像这样的主要
void Main{
Cow c = new Cow();
Console.WriteLine(c.toString());
}
但是当我运行它时,它会将UserQuery+Cow
打印到控制台。
我不知道我做错了什么?这是因为base.toString()
?
答案 0 :(得分:3)
使用override
关键字:
abstract class Animal
{
protected int numberOfPaws;
public abstract String speak();
public override string ToString(){
return "I have " + numberOfPaws + " paws";
}
}
class Cow : Animal
{
public Cow : base(4) {}
public override String speak(){
return "Moo!";
}
public override string ToString(){
return "I am a Cow " + base.ToString();
}
}
答案 1 :(得分:2)
你应该在这里阅读:How To: Override the ToString Method
public override string ToString()
{
return "I have " + numberOfPaws + " paws";
}
您错过了override
关键字