c# - 为什么在C#中调用Grand parent虚函数

标签 c# oop

我有以下代码。谁能回答为什么在这种情况下调用 base-show 方法而不调用 derive-show。在这种情况下,将如何为派生类和基类的显示函数分配内存。

class OverrideAndNew : Derive
{

    public static void Main()
    {
        Derive obj = new Derive1();
        obj.Show();

        Console.ReadLine();
    }
}

class Base
{
    public virtual void Show()
    {
        Console.WriteLine("Base - Show");
    }
}

class Derive : Base
{
    protected virtual void Show()
    {
        Console.WriteLine("Derive - Show");
    }
}

class Derive1 : Derive
{
    protected override void Show()
    {
        Console.WriteLine("Derive1 - Show");
    }
}

最佳答案

因为你调用了它。覆盖方法时不能修改访问修饰符。所以基本上,Derive1 覆盖了 Derive 的 Show 方法。但 derive 从未超越 Base。所以只有一种公共(public) Show 方法,即在 Base 中实现的方法。

你可能想做的是:

class OverrideAndNew
{
    public static void Main()
    {
        Derive obj = new Derive1();
        obj.Show();

        Console.ReadLine();
    }
}

class Base
{
    public virtual void Show()
    {
        Console.WriteLine("Base - Show");
    }
}

class Derive : Base
{
    public override void Show()
    {
        Console.WriteLine("Derive - Show");
    }
}

class Derive1 : Derive
{
    public override void Show()
    {
        Console.WriteLine("Derive1 - Show");
    }
}

请注意,方法签名保持不变。它总是公开的,因为 Base 说它必须公开。它始终具有相同的名称、返回类型和参数(在本例中没有)。

关于c# - 为什么在C#中调用Grand parent虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24594002/

相关文章:

c# - 在哪里定义常量并在任何地方使用它们?

javascript - 如何使用具有对象属性的元素,例如 element.myobj.prop

c# - 在 Windows 窗体中获取 TableLayoutPanel 单元格的高度和宽度

c# - 无法使用 SendKeys 或 SendMessage 以编程方式粘贴非文本对象

c# - 如何从 "Full Screen"中的 C#/WPF 打开 Excel 文件?

c# - VS2013 中的表单设计器放大了吗?

c# - 这是好的设计吗?

c# - 接口(interface)和类之间有什么区别,当我可以直接在类中实现方法时为什么要使用接口(interface)?

c# - 如何调用重写虚方法的 'base implementation'?

python - 创建一个没有类定义的空白类实例