让我们假设我们有以下代码:
abstract class Base1 {
protected int num;
}
class Der1:Base1 {
protected Color color;
protected string name;
}
class Der2:Base1 {
protected DateTime dthen;
}
Run Code Online (Sandbox Code Playgroud)
等等.base1存在一个类型数组,包括从派生自的类创建的许多对象base1.
是否可以toString()仅在基类中定义方法?就像是:
public override string toString()
{
if (this is Der1)
return "num = " + this.num + "color = " + this.color.toString() + " name = " this.name;
if (this is Der2)
return "num = " + this.num + "dthen = " + this.dthen.toString();
// and so on ...
}
Run Code Online (Sandbox Code Playgroud)
非常感谢你 :)
PS这不是一个功课问题.我只是想知道.
执行此操作的唯一方法是强制转换this为每个派生类型.(即使只有成员公开,这才有效)
但是,您确实应该覆盖该方法.