加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何实现基类的虚方法,并在c#中的override方法中获取基本方法实

发布时间:2020-12-15 19:28:02 所属栏目:百科 来源:网络整理
导读:参见英文答案 How to call a parent class function from derived class function?????????????????????????????????????6个 ???????????? How can I call the ‘base implementation’ of an overridden virtual method? ?????????????????????????????????
参见英文答案 > How to call a parent class function from derived class function?????????????????????????????????????6个
>???????????? How can I call the ‘base implementation’ of an overridden virtual method? ????????????????????????????????????6个
我有一个抽象类A,它有部分实现的虚方法,它在类B中继承.我想在派生类中实现虚方法,我应该如何在派生类中获得基本实现.
例如.

public abstract class A
{
    public int Sum { set; get; }
    public virtual void add(int a,int b)
    {
        Sum = a + b;
    }
}
class B : A
{
    public override void add(int a,int b)
    {
        // what should i write here
    }
}

解决方法

覆盖虚方法就是这样,覆盖默认(基本)实现并用新方法替换它.但是,如果您未为虚拟方法提供任何重写的实现,则会自动获得基本实现.所以,你的问题的答案就是首先不要覆盖add方法:

class B : A {}

但是,如果您需要保留基本实现但希望扩展它,则可以使用base关键字从派生类显式调用基本实现.例如:

class B : A
{
    public override void add(int a,int b)
    {
        base.add(a,b);
        DoSomethingElse();
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读