基本方法是否能够使用派生的基础数据成员?

iTa*_*ayb 1 c#

让我们假设我们有以下代码:

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这不是一个功课问题.我只是想知道.

SLa*_*aks 6

执行此操作的唯一方法是强制转换this为每个派生类型.(即使只有成员公开,这才有效)

但是,您确实应该覆盖该方法.

  • +1让CLR处理多态分派 - 它更清晰,更快速,更易于维护. (2认同)
  • 不,`((Der1)this).color`是一个编译错误,即使在`Base1`类中也是如此. (2认同)
  • 是的,根据其子类,这将是一个非常糟糕的设计. (2认同)