调用基函数,那么继承功能 [英] Call base function then inherited function

查看:121
本文介绍了调用基函数,那么继承功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基类和类继承的基础。基类有继承的类可以覆盖多个虚拟功能。然而,在基类的虚函数具有代码必须运行继承的类覆盖被调用之前。是否有某种方式,我可以调用基类的虚函数,然后先继承类覆盖。无需对base.function()的调用。

I have a base class and a class inheriting base. The base class has several virtual functions that the inherited class may override. However, the virtual functions in the base class has code that MUST to run before the inherited class overrides get called. Is there some way that I can call the base classes virtual functions first then the inherited class overrides. Without making a call to base.function().

我知道我可以简单地使两个功能,一个被调用,其他虚拟。但有一种方法可以让我保持相同的名字呢?我知道我可能需要改变周围的一些东西。

I know I can simply make two functions, one that gets called, the other virtual. But is there a way I can keep the same names as well? I know I may need to change some things around.

class myBase
{
    public virtual myFunction()
        { /* must-run code, Called first */ }
}

class myInherited : myBase
{
    public override myFunction()
        { /* don't use base.myFunction();,
        called from base.myFunction(); */ }
}

类似问题的这里

推荐答案

这可以在.NET Framework中找到一个共同的解决办法是在一个公共的方法分割的方法 XXX 和一个受保护的虚拟方法 OnXXX 由公共方法调用。对于你的榜样,它看起来是这样的:

A common solution that can be found in the .NET Framework is to split a method in a public method XXX and a protected, virtual method OnXXX that is called by the public method. For your example, it would look like this:

class MyBase
{
    public void MyMethod()
    {
        // do something
        OnMyMethod();
        // do something
    }

    protected virtual void OnMyMethod()
    {
    }
}

class MyInherited : MyBase
{
    protected override void OnMyMethod()
    {
        // do something
    }
}

这篇关于调用基函数,那么继承功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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