我有这种情况,当从 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/