c# - 调用覆盖方法时如何强制执行方法调用(在基类中)?

标签 c# inheritance overriding method-call

我有这种情况,当从 ImplementClass 调用 AbstractMethod 方法时,我想在 AbstractClass< 中强制执行 MustBeCalled 方法/strong> 被调用。我以前从未遇到过这种情况。谢谢!

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

最佳答案

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

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

这样做会在抽象类中创建所需的面向公众的方法,让抽象类知道如何调用以及以什么顺序调用事物,同时仍然允许具体类提供所需的功能。

关于c# - 调用覆盖方法时如何强制执行方法调用(在基类中)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1141104/

相关文章:

c# - 在 GridView RowDataBound 事件中获取 BoundField 值

c# - 无法实现接口(interface)成员,因为它没有 List<IInterface> 的匹配返回类型

java - 如何调用父类指定的方法?

swift - 为什么我现在必须在 Swift 中覆盖我的 init?

c# - 意外的 Linq OrderBy

c# - 使用索引 C# 返回数组的子集

c# - 将 Fiddler 与 Windows 应用商店单元测试结合使用

java - 在 Java 中强制使用基类方法

android - 如何覆盖/修改 sdk 中的值或方法?

swift - 覆盖 Swift 子类中的属性