覆盖派生类中的toSting

时间:2015-05-12 07:47:19

标签: c# override abstract-class tostring

我有一个抽象类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()

2 个答案:

答案 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关键字