调用重写方法时如何强制执行方法调用(在基类中)? [英] How to enforce a method call (in the base class) when overriding method is invoked?

查看:115
本文介绍了调用重写方法时如何强制执行方法调用(在基类中)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种情况,当<强> AbstractMethod 方式从调用的 ImplementClass 我想强制执行的 MustBeCalled 方式中的抽象类被调用。我以前从未遇到过这种情况。谢谢!

I have this situation that when AbstractMethod method is invoked from ImplementClass I want to enforce that MustBeCalled method in the AbstractClass is invoked. I’ve never come across this situation before. Thank you!

public abstract class AbstractClass
{
    public abstract void AbstractMethod();

    public void MustBeCalled()
    {
        //this must be called when AbstractMethod is invoked
    }
}

public class ImplementClass : AbstractClass
{
    public override void AbstractMethod()
    {
        //when called, base.MustBeCalled() must be called.
        //how can i enforce this?
    }
}


推荐答案

选项是让Abstract类以这种方式进行调用。否则,c#中没有办法要求继承类以某种方式实现方法。

An option would be to have the Abstract class do the calling in this manner. Otherwise, there is no way in c# to require an inherited class to implement a method in a certain way.

public abstract class AbstractClass
{
    public void PerformThisFunction()
    {
        MustBeCalled();
        AbstractMethod();
    }

    public void MustBeCalled()
    {
        //this must be called when AbstractMethod is invoked
    }

    //could also be public if desired
    protected abstract void AbstractMethod();
}

public class ImplementClass : AbstractClass
{
    protected override void AbstractMethod()
    {
        //when called, base.MustBeCalled() must be called.
        //how can i enforce this?
    }
}

这样做会在摘要中创建所需的面向公众的方法class,给出抽象类,了解事物的调用方式和顺序,同时仍允许具体类提供所需的功能。

Doing this creates the desired public facing method in the abstract class, giving the abstract class over how and in what order things are called, while still allowing the concrete class to provide needed functionality.

这篇关于调用重写方法时如何强制执行方法调用(在基类中)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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