Why C# doesn't support base.base?

北慕城南 提交于 2019-12-10 12:43:31

问题


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 display 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.


回答1:


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.)




回答2:


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



来源:https://stackoverflow.com/questions/7648910/why-c-sharp-doesnt-support-base-base

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!