【问题标题】:Calling an overwritten child method from parent class?从父类调用覆盖的子方法?
【发布时间】:2017-11-11 21:19:33
【问题描述】:

我想知道理论上这段代码的输出是什么? 基本上我正在覆盖子类中的一个方法,但我正在调用它 父类中的方法。我希望这个输出是"Child"

public class Animal {
    protected virtual void Activate() {
        Debug.Log("Parent");
    }

    void CallStuff() {
        Activate();
    }
}

public class Frog : Animal {
    override void Activate() {
        Debug.Log("Child");
    }
}

如果我有一个青蛙实例frog 并调用...

frog.CallStuff();

输出会是什么?

【问题讨论】:

  • 这没有什么理论依据。你试过了吗?

标签: c# inheritance overwrite


【解决方案1】:

输出将是“Child”它继承了 Call Stuff 函数但覆盖了 Activate 函数,因此您将获得 Child

【讨论】:

  • 好的,谢谢,顺便说一句,我不知道为什么这会得到如此多的反对票,这是一个合理的问题。
  • 我投了反对票,因为这个问题根本没有理论依据。您可以自己尝试一下并看到结果。
  • @user3312266 因为这是一个非常介绍性的问题,您可以通过运行您在问题中发布的代码来解决这个问题。
  • 我该死的支持它。感谢您的帮助
【解决方案2】:

也许一些例子能解释得最好:

让我们从一个基类开始:

public class Parent {
  public virtual string WhatAmI() {
    return "Parent";
  }

  public string Output() {
    return this.WhatAmI();
  }
}

调用输出方法当然会给你“父母”

new Parent().Output(); // "Parent"

现在让我们重写那个虚拟方法

public class OverridingChild : Parent {
  public override string WhatAmI() {
    return "Child";
}

现在当你调用 Output() 时,它会返回 "Child"

new OverridingChild().Output(); // "Child"

如果你将它转换为父级,你会得到相同的结果:

((Parent) new OverridingChild()).Output(); // "Child"

如果你想要基类的值,你必须从继承类中调用 base:

public class OverridingChild : Parent {
  public override string WhatAmI() {
    return "Child";

  public string OutputBase() {
    return base.WhatAmI();
  }
}

new OverridingChild().OutputBase(); // "Parent"

现在是令人困惑的部分 - 以下是获取任一值的方法,具体取决于编译器认为该对象是什么类:

public class NewMethodChild : Parent {
  // note that "new" keyword
  public new string WhatAmI() {
    return "Child";
}

当编译器认为它是继承类时直接调用该方法可以获得预期的结果:

new NewMethodChild().WhatAmI(); // "Child"

但是如果你将它转换为基类,你会得到 Parent 结果:

((Parent) new NewMethodChild()).WhatAmI(); // "Parent"

如果你调用Output方法,因为它是在Parent类中定义的,它看不到继承类的新WhatAmI方法,所以它也输出基值:

new NewMethodChild().Output(); // "Parent"

希望能解决问题。

【讨论】:

    猜你喜欢
    • 2014-05-11
    • 1970-01-01
    • 1970-01-01
    • 2020-11-04
    • 1970-01-01
    • 1970-01-01
    • 2020-07-22
    • 2017-11-18
    • 2019-10-30
    相关资源
    最近更新 更多