微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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);
}

原文地址:https://www.jb51.cc/csharp/98841.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐