开发者

Polymorphism and c#

Here one more basic question asked in MS interview recently

class A {
    public virtual void Method1(){}

    public void Meth开发者_高级运维od2() {
        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();

gets called because it properly overrides the virtual method 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"); 
    } 
} 


The rule is "overriding member in the most derived class", which in this case would be "B".


B.Method1() is called due to the override.


B.Method1 is called because it is overridden in the class definition.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜