Why does this polymorphic C# code print what it does?

后端 未结 5 1077
逝去的感伤
逝去的感伤 2020-11-30 18:00

I was recently given the following piece of code as a sort-of puzzle to help understand Polymorphism and Inheritance in OOP - C#.

//         


        
5条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-30 18:38

    OK, the post is a bit old, but it's an excellent question and an excellent answer, so I just wanted to add my thoughts.

    Consider the following example, which is the same as before, except for the main function:

    // No compiling!
    public class A
    {
        public virtual string GetName()
        {
            return "A";
        }
    }
    
    public class B:A
    {
        public override string GetName()
        {
            return "B";
        }
    }
    
    public class C:B
    {
        public new string GetName()
        {
            return "C";
        }
    }
    
    void Main()
    {
        Console.Write ( "Type a or c: " );
        string input = Console.ReadLine();
    
        A instance = null;
        if      ( input == "a" )   instance = new A();
        else if ( input == "c" )   instance = new C();
    
       Console.WriteLine( instance.GetName() );
    }
    // No compiling!
    

    Now it's really obvious that the function call cannot be bound to a specific function at compile time. Something must be compiled however, and that information can only depend on the type of the reference. So, it would be impossible to execute the GetName function of class C with any reference other than one of type C.

    P.S. Maybe I should've used the term method in stead of function, but as Shakespeare said: A function by any other name is still a function :)

提交回复
热议问题