继承事件处理程序

时间:2014-01-29 13:24:43

标签: c# .net events inheritance

我试图为不同的报告编写抽象类。

我有一个方法

protected Tuple<byte[], string, string> RenderReport()

有这样的行

var localReport = new LocalReport { ReportPath = _reportLocalFullName };
...
localReport.SubreportProcessing += localReport_SubreportProcessing;

派生类必须在localReport_SubreportProcessing中编写自己的代码。

我不确定如何在这里进行继承。有人可以帮忙吗?

3 个答案:

答案 0 :(得分:5)

而不是方法:

private void localReport_SubreportProcessing(...) {...}

改为考虑:

protected virtual void OnSubreportProcessing(...) {...}

现在您的子类可以使用:

protected override void OnSubreportProcessing(...) {...}

答案 1 :(得分:1)

您可以调用常用方法,在base课程中覆盖该方法。

所以在localReport_SubreportProcessing中,请致电ProcessSubreport

private void localReport_SubreportProcessing(object sender, EventArgs e)
{
    this.ProcessSubreport();
}

protected virtual void ProcessSubreport()
{ }

并在派生类中覆盖它:

protected override void ProcessSubreport()
{ }

答案 2 :(得分:0)

尝试如下。

public abstract class BaseReport
{
  ......
  protected Tuple<byte[], string, string> RenderReport()
  {
    var localReport = new LocalReport { ReportPath = _reportLocalFullName };
    ...
    localReport.SubreportProcessing += localReport_SubreportProcessing;
    ...
  }

  protected abstract void LocalReport_SubreportProcessing(object sender, EventArgs e);
}

public class DerivedReport1 : BaseReport
{
  protected override void LocalReport_SubreportProcessing(object sender, EventArgs e)
  {
    // Report generation logic for report1.
  }
}

public class DerivedReport2 : BaseReport
{
  protected override void LocalReport_SubreportProcessing(object sender, EventArgs e)
  {
    // Report generation logic for report2.
  }
}