在 class 中使用覆盖而不是事件订阅

Use override instead of event subscription in a class

目前我正在挣扎,是否要覆盖现有方法,例如 OnActivate 而不是在同一个 class.

中订阅 event

例如我有下面的class,它实现了一个事件:

public class Base
{
    public delegate void DoSomeThing(object sender, EventArgs e);

    public event DoSomeThing DoSomeThingEventHandler;

    public virtual void OnDoSomeThing(EventArgs e)
    {
        if (DoSomeThingEventHandler != null)
        {
            DoSomeThingEventHandler(this, e);
        }
    }
}

我有一个 class 派生自 Base,如果 DoSomeThing 被调用,它希望得到通知。我应该覆盖 DoSomeThing 还是应该订阅事件:

解决方法一:

public class B1 : Base
{
    public override void OnDoSomeThing(EventArgs e)
    {
        // Do some stuff here

        base.OnDoSomeThing(e);
    }
}

第二种解决方案

public class B2 : Base
{
    public B2()
    {
        DoSomeThingEventHandler += B2_DoSomeThingEventHandler;
    }

    private void B2_DoSomeThingEventHandler(object sender, EventArgs e)
    {
        // Do some thing here
    }
}

您更喜欢解决方案 B1 还是 B2

谢谢大家!

在这种情况下,覆盖是一个更好的选择,但首先执行基础 class 实现,这样你就不会破坏任何东西,然后在派生的 class 中做任何你想做的事情,比如:

public override void OnDoSomeThing(EventArgs e)
{

  base.OnDoSomeThing(e);

  // write here whatever needed

}