当派生 class 中的方法被调用时,基 class 是否有可能得到通知?

Is it possible a base class gets informed when a method in derived class is called?

考虑以下小设计:

public class Parent
{
  public event EventHandler ParentWentOut;
  public virtual void GoToWork()
  {
     ParentWentOut();
  }
}

public class Mother : Parent
{
   public override void GoToWork()
   {
     // Do some stuff here
     base.GoToWork(); // <- I don't want to write this in any derived class. 
                      //    I want base class's method to be automatically called.
   }
}

是否有任何机制可以使 Parent.GoToWork 方法在后代的覆盖版本(此处 Mother class)中完成时隐式自动调用?

如果除 C# 之外还有任何其他语言能够做到这一点,我将不胜感激。

因此,到目前为止,访问基 class 的唯一方法是通过 base 关键字,该关键字如何保存对基 class 的引用,该引用通过调用其构造函数进行初始化。

因此你的答案是否定的。

你可以尝试实现这样的东西

public class Parent
{
   public event EventHandler ParentWentOut;
   public void GoToWork()
   {
     BeforeParentWentOut();
     ParentWentOut();
     AfterParentWentOut();         
   }

   protected virtual void BeforeParentWentOut()
   {
      // Dont do anything, you can even make it abstract if it suits you
   }

   protected virtual void AfterParentWentOut()
   {
      // Dont do anything, you can even make it abstract if it suits you
   }
}



public class Mother : Parent
{
   protected override void BeforeParentWentOut()
   {
      // Do some stuff here
   }
}

您也可以在 Mother class 上订阅您自己的活动并对此做出反应。

编辑:更新受保护,添加了 before/after 方法来处理何时向父实现添加代码

我建议使用两种方法 - 一种用于 public API,另一种用于方法的内部功能。

public class Parent
{
  public event EventHandler ParentWentOut;
  public void GoToWork()
  {
     GoToWorkOverride();
     ParentWentOut();
  }

  protected virtual void GoToWorkOverride()
  {}
}

public class Mother : Parent
{
   protected override void GoToWorkOverride()
   {
       // Do some stuff here
   }
}