简体   繁体   中英

Polymorphism and c#

Here one more basic question asked in MS interview recently

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 which function gets called? Sorry for the typos.

B.Method1();

被调用,因为它正确地覆盖了虚方法A.Method1();

In this case B.Method1 gets called. This is because even though the variable is typed as A the actual type of the instance is B . The CLR polymorphically dispatches calls to Method1 based on the actual type of the instance, not the type of the variable.

Method1 from class B will be called, as you can see by running the below program:

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"); 
    } 
} 

规则是“覆盖最派生类中的成员” ,在本例中为“B”。

B.Method1()由于覆盖而被调用。

调用B.Method1是因为它在类定义中被重写。

The question is a little ambigious...but...

obk.method2() is called. In turn, it calls obk.Method1, which, since it is an instance of B, has been overridden by B.Method1. So B.Method1 is what eventually gets called.

As everybody else has said, B.Method2 gets called. Here is a few other pieces of information so you understand what's going on:

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

These will both call B.Method1() because it was properly overridden. In order to call A's Method1, there must be a base.Method1() call made from B (which is often but not always done in B.Method1's implementation).

If, however, B was defined in this way:

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

... then A's Method1() would be called because Method1 was not actually overridden, it was hidden and tucked away outside the rules of polymorphism. In general, this is typically a bad thing to do. Not always, but make sure you know very well what you're doing and why you're doing it if you ever do something like this.

On the flip side, using new in this way makes for some interesting interview questions as well.

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