Polymorphism and C #

Here's another key question asked recently in an MS interview.

class A {
    public virtual void Method1(){}

    public void Method2() {
        Method1();
    }
}

class B:A {
    public override void Method1() { }
}

class main {
    A obk = new B();
    obk.Method2(); 
}

So what function is being called? Sorry for the typos.

+5
source share
8 answers
B.Method1();

called because it correctly overrides the virtual method A.Method1();

+12
source

In this case, calls B.Method1. This is because although the variable is typed as A, the actual type of the instance B. The CLR makes polymorphic calls based Method1on the actual type of the instance, not the type of the variable.

+5
source

Method1 B , , :

class Program
{
    static void Main(string[] args)
    {
        var b = new B();
        b.Method2();

        Console.ReadLine();
    }
}

class A 
{ 

    public virtual void Method1()
    {
         Console.WriteLine("Method1 in class A");
    } 

    public void Method2() 
    { 
         Method1(); 
    } 
}

class B : A 
{ 
    public override void Method1() 
    { 
         Console.WriteLine("Method1 in class B"); 
    } 
} 
+4

" , " B ".

+3

B.Method1() - .

+2

B.Method1 , .

+1

... ...

obk.method2(). , obk.Method1, , B, B.Method1. B.Method1 - , .

+1

, B.Method2. , , :

((A)B).Method2();
B.Method2();

B.Method1(), . Method1, .Method1(), B ( , B.Method1).

, , B :

class B:A {
new public void Method1() { }

... then A Method1 () will be called because method 1 was not actually overridden, it was hidden and hidden outside the rules of polymorphism. In general, this is usually bad. Not always, but make sure that you know very well what you are doing and why you are doing it if you ever do something like this.

On the other hand, using the new in this way also creates interesting interesting questions.

0
source

All Articles