c# - 抽象类中的公共(public)事件

标签 c# events delegates action abstract-class

我在抽象类中声明了事件:

public abstract class AbstractClass
{
    public event Action ActionEvent;
}

public class MyClass : AbstractClass
{
    private void SomeMethod()
    {
        //Want to access ActionEvent-- Not able to do so
        if (ActionEvent != null)
        {
        }

    }
}

我想在派生中访问这个基类事件。此外,我想在 MyClass 的其他派生类中访问此事件:

MyClass.ActionEvent += DerivedMethod()

请帮助我了解如何使用抽象类中定义的事件。

最佳答案

一个经常使用的模式如下所示(您会在 System.Windows.Forms 命名空间的类中看到很多)。

public abstract class MyClass
{
    public event EventHandler MyEvent;

    protected virtual void OnMyEvent(EventArgs e)
    {
        if (this.MyEvent != null)
        {
            this.MyEvent(this, e);
        }
    }
}

然后您可以像这样在派生类中使用它,可选择地扩展行为:

public sealed class MyOtherClass : MyClass
{
    public int MyState { get; private set; }

    public void DoMyEvent(bool doSomething)
    {
        // Custom logic that does whatever you need to do
        if (doSomething)
        {
            OnMyEvent(EventArgs.Empty);
        }
    }

    protected override void OnMyEvent(EventArgs e)
    {
        // Do some custom logic, then call the base method
        this.MyState++;

        base.OnMyEvent(e);
    }
}

关于c# - 抽象类中的公共(public)事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29831066/

相关文章:

C# 检查 Datetime.now 是否为特定时间

c# - nuget 包安装生成的空数据上下文

c# - 如何使用 Linq to Entities 动态检索特定子类型的所有记录?

android - 在 Android 日历中插入多个事件

Matlab:OOPS:事件 block :在运行时动态(以编程方式)添加事件

c# - 为什么我的事件抛出空错误?

c# - 将事件处理程序作为方法参数传递

c# - 从委托(delegate)中读取返回值

c# - BeginInvoke 和 Thread.Start 之间的区别

c# - Resharper 在大型解决方案上抛出 OutOfMemoryException