Virtual method called from derived instead of base

偶尔善良 提交于 2019-11-28 13:54:14

The method implementation is chosen based on the execution-time type of the object. That's a large part of the point of it. Anyone can use:

public void Foo(Base b)
{
    b.VirtualMethod();
}

... and not need to know or care what the execution type is, because polymorphism will take care of it.

I know i can call the Base's virtual method from the derived by calling base.VirtualMethod() but can I call it from outside?

No (at least, not without some horribly hackery to call the virtual method non-virtually), and that's a deliberate part of encapsulation. The overriding implementation has effectively replaced the original implementation for that object.

If you want to access base implementation you should not use override, you should use new. Override overrides any parent implementation, new 'hides' the parent implementation so that you can access the implementation by casting as the parent object then invoking the method.

internal class Program
{
    private static void Main(string[] args)
    {
        Derived d = new Derived();
        d.VirtualMethod();
        ((Base) d).VirtualMethod();

        Console.ReadLine();
    }

    private class Base
    {
        public virtual void VirtualMethod()
        {
            Console.WriteLine("Base virtual method");
        }
    }

    private sealed class Derived : Base
    {
        public new void VirtualMethod()
        {
            Console.WriteLine("Overriden method");
        }
    }
}

This will output:

Overriden method
Base virtual method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!