调用基函数然后继承函数 [英] Call base function then inherited function

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

问题描述

我有一个基类和一个继承基类的类.基类有几个被继承的类可以覆盖的虚函数.但是,基类中的虚函数具有必须在调用继承类覆盖之前运行的代码.有什么方法可以先调用基类虚函数,然后再调用继承的类.无需调用 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天全站免登陆