简体   繁体   中英

Virtual members dispatch on run-time type

One of the features/topics discussed in OOP are Virtual members. I am looking at a statement as following:

Virtual members dispatch on run-time type

Does it mean a virtual method rely on type of object(s) it is accepting or dealing with rather variable type?

Any correction or comment will be appreciated.

Thanks, Amit

No. It has nothing to do with the parameters that the method accepts as those should be the same for each implementation. It means that the virtual method will be resolved at run time based on the type the method is being called on. Consider this:

public class Parent
{
    public virtual string SayHi()
    {
        return "Hi!";
    }
}

public class NiceChild : Parent
{
    public override string SayHi()
    {
        return "Hello World!";
    }
}

public class MeanChild : Parent
{
    public override string SayHi()
    { 
        return "You suck!";
    }
}

Now, we have a method:

public void PrintHi(Parent instance)
{
    Console.WriteLine(instance.SayHi());
}

You could call that method one of three ways but not know the outcome until runtime if all you saw was the method above:

PrintHi(new Parent()); // Hi
PrintHi(new NiceChild()); // Hello World!
PrintHi(new MeanChild()); // You suck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM