Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
454 views
in Technique[技术] by (71.8m points)

c# - Virtual method called from derived instead of base

Can someone explain to me why is the overridden method being called when I cast the class into the base one:

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

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

    static void Main(String[] args)
    {
        Derived d = new Derived();
        ((Base)d).VirtualMethod();
    }

I mean this code prints:

Overriden method

and not

Base virtual method

Its a run-time or compile-time future?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...