public abstract class BasePage : System.Web.UI.Page, IBasePage
{
protected override void OnInit(EventArgs e)
{
// Do stuff
Method1();
Method2();
Method3();
// Call System.Web.UI.Page.OnInit
base.OnInit(e);
}
}
This works great for all my child classes/pages, but there are a few scenario's where I'd only like to call a specific set of methods, as illustrated here:It is obvious that the last base.OnInit(e) call will have the undesired effect. Being 6:23 PM, after coding all day, my fried brain's initial thought was to bypass the base class' OnInit(e) method and to call the grandparent's OnInit(e) method directly.public class MyPage: BasePage
{
protected override void OnInit(EventArgs e)
{
// Ommit Method2()
Method1();
Method3();
// This calls BasePage.OnInit, which makes
// redudant calls to Method1() and Method3(),
// and the undesired call to Method2().
base.OnInit(e);
}
}
An obvious faux pas. Whenever venturing into the "grandparent" or "grandchild" realm (more than one degree of seperation), you're probably going down the wrong path.
The proper and easy approach is merely to move the method calls out to a seperate method, which one overrides in the child class like so:
public abstract class BasePage : System.Web.UI.Page, IBasePage
{
protected override void OnInit(EventArgs e)
{
// Do stuff
Initialize();
// Call System.Web.UI.Page.OnInit
base.OnInit(e);
}
protected virtual void Initialize()
{
Method1();
Method2();
Method3();
}
}
public class MyPage: BasePage
{
protected override void Initialize()
{
// Do stuff
Method1();
Method3();
}
}
No comments:
Post a Comment