我想用抽象方法声明一些继承抽象类的类。 我还希望子类中的某些方法自动调用公共(public)代码(即日志代码)
public abstract class AbstractClass
{
public abstract void AbstractMethod();
public void CommonCode()
{
//do something
}
}
public class ChildClass : AbstractClass
{
public void AbstractMethod()
{
//automatically call CommonCode in base class
//do something
}
}
事件可以帮助我吗?
问候
最佳答案
不必太花哨,您可以使抽象方法成为您希望继承者执行的操作的“核心”,并从基类的包装器方法中调用它。例如:
public abstract class AbstractClass
{
// Note that this protected since consumers won't call it directly
protected abstract void AbstractMethod();
// Instead, consumers will use this method which calls CommonCode
// before the abstract method.
public void AbstractMethodWrapper()
{
CommonCode();
AbstractMethod();
}
public void CommonCode()
{
//do something
}
}
public class ChildClass : AbstractClass
{
protected override void AbstractMethod()
{
// The wrapper method in the base handles calling common code
//do something
}
}
关于C#抽象方法和公共(public)代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14753830/