0
public abstract class Base {
   public void execute() {
      //'preexecute code'
      child.execute();
      //'postexecute code'
   }
}

public class Child : Base {
{
   public void execute() {
      //'Some child specific code'
   }
}

Is there any way in C# to support an execution model like above where you call a function in the child class from the base class. The "preexecute code" and "postexecute code" is common and should be ran every time "execute" is called.

4

2 回答 2

10

我向您推荐一个从基础调用的抽象方法(称为模板方法模式):

abstract class Base {
  void Foo() {
    DoSomething();
    Bar();
    DoSomethingElse();
  }

  protected abstract void Bar();
}

class Child : Base {
  protected override void Bar() {
    DoSomethingChildSpecific();
  }
}

Bar您可以在(模板方法模式中的原始操作)中为每个孩子实现一个非常具体的部分,并在正确的上下文中调用它。因此,消费者不能弄乱执行顺序,这与他们能够覆盖自身不同。BaseFooFoo

于 2013-05-10T08:41:23.297 回答
0

我想你在找

public abstract class Base {
   public abstract void execute();
}

public class Child : Base {
{
   public override void execute() {
      //'Some child specific code'
   }
}
于 2013-05-10T08:41:13.397 回答