我有以下页面
public partial class GenericOfflineCommentary : OfflineFactsheetBase
{
}
其中OfflineFactsheetBase
定义为
public class OfflineFactsheetBase : System.Web.UI.Page
{
public OfflineFactsheetBase()
{
this.Load += new EventHandler(this.Page_Load);
this.PreInit += new EventHandler(this.Page_PreInit);
}
protected void Page_PreInit(object sender, EventArgs e)
{
if (Request.QueryString["data"] != null)
{
this.PageData = StringCompressor.DecompressString(Request.QueryString["data"]);
this.ExtractPageData();
}
}
}
OfflineFactsheetBase
具有以下virtual
方法:
public virtual void ExtractPageData()
{
// get stuff relevant to all pages that impmement OfflineFactsheetBase
}
在所有影响OfflineFactsheetBase的页面中实现,如下所示:
public partial class GenericOfflineCommentary : OfflineFactsheetBase
{
public override void ExtractPageData()
{
// get stuff relevant to an OfflineCommentary page.
}
}
目前,只有GenericOfflineCommentary
的ExtractPageData()被触发。如何将其修改为首先运行OfflineFactsheetBase
的ExtractPageData()然后再运行GenericOfflineCommentary
?
编辑:我试图避免在每个实现者中调用base.ExtractPageData()
。这可能吗?
答案 0 :(得分:3)
使ExtractPageData
方法非虚拟,并调用ExtractPageDataInternal
虚拟方法:
public void ExtractPageData()
{
// get stuff relevant to all pages that impmement OfflineFactsheetBase
// base implementation
...
// call derived class implementation
this.ExtractPageDataInternal();
}
protected virtual void ExtractPageDataInternal()
{
// implementation to be defined by derived class
}
派生类只会覆盖ExtractPageDataInternal
,而不是ExtractPageData
,因此基本实现将始终执行
答案 1 :(得分:0)
澄清后修订
public class OfflineFactsheetBase : System.Web.UI.Page
{
public OfflineFactsheetBase ( )
{
this.Load += new EventHandler ( this.Page_Load );
this.PreInit += new EventHandler ( this.Page_PreInit );
}
protected void Page_PreInit ( object sender, EventArgs e )
{
if ( Request.QueryString [ "data" ] != null )
{
this.PageData = StringCompressor.DecompressString ( Request.QueryString [ "data" ] );
this.ExtractPageData ( );
}
}
public void ExtractPageData ( )
{
// get stuff relevant to all pages that implement OfflineFactsheetBase
// ....blah...
InternalExtractPageData ( );
}
// Could be abstract if the class where
protected virtual void InternalExtractPageData ( )
{
// get stuff relevant to all pages that impmement OfflineFactsheetBase
}
}
public partial class GenericOfflineCommentary : OfflineFactsheetBase
{
public override void ExtractPageData ( )
{
// get stuff relevant to an OfflineCommentary page.
}
}
OfflineFactsheetBase是抽象的吗?如果是这样,请将ExtractPageData保护为抽象,并从基础上的公共方法调用它,请参阅this SO question and answer