为什么C#不支持base.base? [英] Why C# doesn't support base.base?

查看:275
本文介绍了为什么C#不支持base.base?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我测试code是这样的:

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

和试图从A类(祖父母的方法)的C法测试呼叫。但它不工作。请告诉我一个方法来调用祖父母虚方法。

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.

推荐答案

您不能 - 因为它会破坏封装。如果B类要强制执行的某种不变的(或其他)的测试这将是pretty的严峻,如果C类可能只是绕过它。

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

这篇关于为什么C#不支持base.base?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆