简体   繁体   English

虚拟成员按运行时类型调度

[英]Virtual members dispatch on run-time type

One of the features/topics discussed in OOP are Virtual members. OOP中讨论的功能/主题之一是虚拟成员。 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!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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