gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:08:52 26 4
gpt4 key购买 nike

考虑以下小设计:

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 类)的覆盖版本中完成时隐式自动调用?

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

最佳答案

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

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 类上订阅您自己的事件并对此使用react。

编辑:更新 protected ,添加之前/之后的方法来处理何时将代码添加到父实现

关于c# - 当派生类中的方法被调用时,基类是否有可能得到通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32887314/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com