c# – 为什么调用基类方法而不是派生类方法?

期待“来自派生的你好”.但是得到“基地的你好”.
class Program
{
    interface IBase
    {
        void Method();
    }

    public class Base: IBase
    {
        public virtual void Method()
        {
            Console.WriteLine("Hello from the base.");
        }
    }

    public class Derived : Base
    {
        public virtual new void Method()
        {
            Console.WriteLine("Hello from the derived.");
        }
    }

    static void Main(string[] args)
    {
        IBase x = new Derived();
        x.Method();
    }
}

那么为什么不调用派生类的方法呢?更重要的是,如何在不将x转换为Derived类型的情况下调用派生类方法

在我的实际应用中,IBase有几个其他相关方法,Derived只替换了IBase中的两个方法.

解决方法

当您使用new修饰符时,您明确指出该方法不是该层次结构的虚拟分派链的一部分,因此在基类中使用相同名称调用方法将不会导致重定向到子类.如果使用override而不是new标记方法,那么您将看到您希望看到的虚拟分派.

您还需要从派生类的方法删除虚拟,因为您无法将覆盖方法标记为虚拟(它已经是).

如果您真的不想覆盖该方法,那么在您的情况下,根本不使用继承可能更合适.您可能只想使用接口:

public interface IFoo
{
    void Foo();
}

public class A : IFoo
{
    public void Foo()
    {
        Console.WriteLine("I am A,hear me roar!");
    }
}

public class B : IFoo
{
    public void Foo()
    {
        Console.WriteLine("I am B,hear me roar!");
    }
}

private static void Main(string[] args)
{
    IFoo foo = new A();
    foo.Foo();

    foo = new B();
    foo.Foo();

    Console.WriteLine();
    Console.WriteLine("Press any key to exit . . .");
    Console.ReadKey(true);
}

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...