gpt4 book ai didi

c# - 子/父事件引发

转载 作者:行者123 更新时间:2023-11-30 17:04:59 29 4
gpt4 key购买 nike

我有一个带有多个子类的父抽象类。最终,我希望通过 GUI 中的进度条显示子类中完成的进度。

我目前所做的,我意识到这是行不通的,是在父类中声明为每个子类将覆盖的虚拟方法的事件方法定义。所以像:

public abstract class Parent
{
public event EventHandler someEvent;

protected virtual void OnSomeEvent(object sender, EventArgs e)
{
EventHandler eh= someEvent;
if (eh!= null)
{
eh(this, e);
}
}
}

我的 child 类有这样的东西:

  protected override void OnSomeEvent(object sender, EventArgs e)
{
base.OnSomeEvent(sender, e);
}

并且该事件在子类的某处引发。

但是,由于父类是抽象的,我将无法从我的 GUI 中监听事件,因为我无法创建抽象类的实例。

我是否完全偏离了路线和/或是否有其他方法可以做到这一点?

最佳答案

您可以从子实例附加到事件。

public abstract class Parent
{
public event Action Something;

public void OnSomething()
{
if (Something != null)
{
Something();
}
}
}
public class Child : Parent
{

}

Child c = new Child();
c.Something += () => Console.WriteLine("Got event from child");
c.OnSomething();
> Got event from child

您甚至可以将其声明为包含子项的 Parent 类型:

Parent c2 = new Child();
c2.Something += () => Console.WriteLine("Got event from Parent type");
c2.OnSomething();
> Got event from Parent type

抽象类只是一个代码模板,它被复制到从它继承的每个类中(简单来说)。可以这样想,您的所有 Child 类都包含 Parent 中存在的代码的相同副本。


请注意,这还将为 Child 的每个实例生成一个唯一的事件处理程序。为从 Parent 派生的所有 Child 设置一个静态事件处理程序看起来像这样,并且不需要 Child 中的代码:

public abstract class Parent
{
public static event Action Something;

public static void OnSomething()
{
if (Something != null)
{
Something();
}
}
}

然后,你可以做这样的事情,例如:

Parent.Something += () => Console.WriteLine("This will be invoked twice.");

Child c = new Child();
Child c2 = new Child();
c.OnSomething();
c2.OnSomething();

> This will be invoked twice.
> This will be invoked twice.

这两个对象/事件调用将调用相同的事件处理程序,即使它们来自不同的子级也是如此。

关于c# - 子/父事件引发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16901760/

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