查看以下(伪)模式:
public abstract class Animal {
public abstract AnimalType { get; }
public abstract override string ToString() {
return String.Format("{0}={1}", AnimalType, this.ToString());
^
// does this even work?
}
}
这将迫使从它派生的每个类看起来像这样:
public sealed class Horse : Animal {
// horse specific declaration
private string _name;
private int _age;
// forced
public override AnimalType {
get { return AnimalType.Horse; }
}
// horse specific declaration
public Name {
get { return _name; }
public Horse(string name, string age) {
_name = name;
_age = age;
}
// forced
public override string ToString() {
return String.Format("{0}({1}", _name, _age);
}
}
这将产生以下输出:
Horse =MyHorseName(3);
Tiger =SomeOtherAttributesBecauseTigerIsDifferent
问题是:当我想在派生类中强制 ToString() 时,我不能在基类中拥有任何功能。我希望派生类提供它自己的字符串表示形式,但仍然希望有一个字符串表示形式告诉我,在这种情况下,它是什么类型的动物。