简体   繁体   English

类型转换和多态 function 调用之间的区别?

[英]The difference between type casting and a polymorphic function call?

I'm reading Rihter's book on c# and I am wondering how type casting works.我正在阅读 Rihter 关于 c# 的书,我想知道类型转换是如何工作的。

Say I have this code:说我有这段代码:

    class Parent
    {
        public virtual void DoStuff()
        {
            //... some code
        }
    }

    class Child : Parent
    {
        public override void DoStuff()
        {
            // .. some different code
        }
    }

Now in the Main() function I call this:现在在 Main() function 我称之为:

        Parent child = new Child();
        child.DoStuff();

How is this different from type casting?这与类型转换有何不同? According to Rihter the CLR will follow the child's link to the child's type-object (Child) in memory and retrieve the pointer to the Child.DoStuff() version of the method.根据 Rihter 的说法,CLR 将在 memory 中跟踪子对象到子对象类型对象 (Child) 的链接,并检索指向该方法的 Child.DoStuff() 版本的指针。 To me that sounds like the same operation as this:对我来说,这听起来像是与此相同的操作:

        ((Child)child).DoStuff();

Where am I wrong?我哪里错了?

How is this different from type casting?这与类型转换有何不同?

Polymorphism is very different than type casting and a key foundation of OO programming languages.多态性与类型转换有很大不同,它是 OO 编程语言的关键基础。 Your example doesn't really showcase anything about the usefulness of the feature.您的示例并没有真正展示该功能的实用性。

Consider the following example:考虑以下示例:

 abstract class Animal {
     public abstract string MakeSound(); }

 void PrintSound(Animal animal) { Console.WriteLine(animal?.MakeSound(); }

And now the typical scenario of a callsite with an argument only known at runtime:现在调用点的典型场景只有在运行时才知道参数:

var animal = makeUserChooseAnimal(); //no idea what animal this will be
PrintSound(animal);

Where exactly would you fit in the cast you are asking about?您究竟适合您所询问的演员阵容中的哪个位置? But polymorphism and the virtual call will make it possible, that no matter what animal is really passed into PrintSound , the appropiate MakeSound() will be called.但是多态性和虚拟调用将使之成为可能,无论真正将什么动物传递给PrintSound ,都会调用适当的MakeSound()

Now, if what you are interested in is understanding how the CLR figures out what method to call, then I'd recommend you read Eric Lippert's three part series on the subject, starting here .现在,如果您感兴趣的是了解 CLR 如何确定要调用的方法,那么我建议您阅读 Eric Lippert 关于该主题的三部分系列,从这里开始。

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

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