Domanda

class A 
 {
   public virtual void WhoAreYou() { Console.WriteLine("I am an A"); }
 }
class B : A
{
  public override void WhoAreYou() { Console.WriteLine("I am a B"); }
}
class C : B
{
 public new virtual void WhoAreYou() { Console.WriteLine("I am a C"); }
}
class D : C 
{
  public override void WhoAreYou() { Console.WriteLine("I am a D"); }
}


C c = new D();
c.WhoAreYou();// "I am a D"
A a = new D();
a.WhoAreYou();// "I am a B" !!!!

How the reference is allocated internally,reference A contains the reference of B? Can any one explain Whats going On?

È stato utile?

Soluzione

In class C, the method WhoAreYou() doesn't override the base class method, as it is defined with new keyword which adds a new method with the same name which hides the base class method. That is why this:

C c = new D();
c.WhoAreYou();// "I am a D"

invokes the overridden method in D which overrides its base class method defined with new keyword.

However, when the target type is A, then this:

A a = new D();
a.WhoAreYou();// "I am a B" !!!!

invokes the overridden method in B, as you're calling the method on a of type A whose method is overriden by B.

Altri suggerimenti

Your class C WhoAreYou() method is 'new', and therefor hiding the one from B. That means that the override in class D is overriding C's method instead of B's (which is overriding A's).

Since you have a reference to an A, the furthest down the hierarchy of it's WhoAreYou() function is the one in class B.

http://msdn.microsoft.com/en-us/library/435f1dw2.aspx

It is mean, that the C's

public new virtual void WhoAreYou(){}

breaks the chain of virtual methods.

When you call the method WhoAreYou() of D by reference of A. The virtuality starts work, but it breaks at C.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top