gpt4 book ai didi

c# - 如何在调用函数时自动调用事件?

转载 作者:太空狗 更新时间:2023-10-29 22:20:48 26 4
gpt4 key购买 nike

我有这样的代码:

public class Foo
{
public SomeHandler OnBar;

public virtual void Bar()
{
}
}

Foo 是一个基类,因此其他类可能继承自它。
我希望在调用 Bar() 时始终触发 OnBar 事件,即使它没有在 Bar 中显式调用也是如此。
怎么做到的?

最佳答案

一个常见的模式是拥有一个非虚拟方法,它会执行您想要调用虚拟方法的操作。子类可以重写内部方法来改变功能,但是公共(public)方法可以是非虚拟的,总是首先引发事件。

public class Foo
{
public SomeHandler OnBar;

public void Bar()
{
if (OnBar != null)
{
OnBar(this, EventArgs.Empty);
}
BarImpl();
}

protected virtual void BarImpl()
{
}
}

关于c# - 如何在调用函数时自动调用事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3223486/

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