[英]Is it possible a base class gets informed when a method in derived class is called?
Consider the following little design: 考虑以下小设计:
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.
}
}
Is there any mechanism to make Parent.GoToWork
method implicitly and automatically be called whenever this method finishes in overridden version of the descendants (here Mother
class) ? 有没有任何机制可以隐式地自动调用
Parent.GoToWork
方法,只要这个方法在后代的重写版本(这里是Mother
类)中完成?
If there is any other language than C# able to do so, I'll be very thankful to know. 如果有其他语言而不是C#能够这样做,我将非常感谢知道。
You can try to implement something like this 你可以尝试实现这样的东西
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
}
}
Also you can subscribe to your own event on the Mother class and react to that. 您也可以在Mother类上订阅自己的活动并对此作出反应。
EDIT: update for protected, added before/after methods to handle when to add code to the parent implementation 编辑:更新为受保护,添加之前/之后的方法来处理何时向父实现添加代码
I would suggest having two methods - one for the public API and one for the internal functioning of the method. 我建议有两种方法 - 一种用于公共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
}
}
So, far the only way to access the base class is through the base keyword which some how hold a reference to base class which is initialized by calling its constructor. 因此,访问基类的唯一方法是通过base关键字,其中一些如何保存对通过调用其构造函数初始化的基类的引用。
Thus your answer is no. 因此你的答案是否定的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.