I tested code like this:
class A
{
public A() { }
public virtual void Test ()
{
Console.WriteLine("I am A!");
}
}
class B : A
{
public B() { }
public override void Test()
{
Console.WriteLine("I am B!");
base.Test();
}
}
class C : B
{
public C() { }
public override void Test()
{
Console.WriteLine("I am C!");
base.base.test(); //I want to di开发者_如何学JAVAsplay here "I am A"
}
}
And tried to call from C method Test of A class (grandparent's method). But It doesn't work. Please, tell me a way to call a grandparent virtual method.
You can't - because it would violate encapsulation. If class B wants to enforce some sort of invariant (or whatever) on Test
it would be pretty grim if class C could just bypass it.
If you find yourself wanting this, you should question your design - perhaps at least one of your inheritance relationships is inappropriate? (I personally try to favour composition over inheritance to start with, but that's a separate discussion.)
One option is to define a new method in B as shown below
class B : A
{
public B() { }
public override void Test()
{
Console.WriteLine("I am B!");
base.Test();
}
protected void TestFromA()
{
base.Test()
}
}
and use TestFromA()
in C
精彩评论