I had an interview a week ago and one of the questions was what the difference between OnInit, Page_Init and PreRender. which one is preferable?
问题:
回答1:
Page_Init
is an event handler for the Page.Init
event, you typically see it if you add a handler within the class itself.
OnInit
is a method that raises the Init
event.
The two can be seen as being equivalent if used within a subclass, but there is a difference: only Init
is exposed to other types, the OnInit
method is protected and is responsible for raising the event, so if you override OnInit
and fail to call base.OnInit
then the Init
event won't be fired. Here's how it looks like:
public class Page {
public event EventHandler Init;
public event EventHandler Load;
protected virtual void OnInit(Object sender, EventArgs e) {
if( this.Init != null ) this.Init(sender, e);
}
protected virtual void OnLoad(Object sender, EventArgs e) {
if( this.Load != null ) this.Load(sender, e);
}
public void ExecutePageLifecylce() {
this.OnInit();
// do some houskeeping here
this.OnLoad();
// further housekeeping
this.Dispose();
}
}
public class MyPage : Page {
public MyPage() {
this.Init += new EventHandler( MyPage_Init );
}
private void MyPage_Init(Object sender, EventArgs e) {
// No additional calls are necessary here
}
protected override void OnLoad(Object sender, EventArgs e) {
// you must make this following call for any .Load event handlers to be called
base.OnLoad(sender, e);
}
}
Generally overriding the OnLoad
/ OnInit
methods is faster (but this is a microptimisation, you're only saving a couple of extra instructions for delegate dispatch) and many "purists" will argue using events unnecessarily is just ugly :)
Another advantage of not using events is avoiding bugs caused by AutoEventWireUp
which can cause events to be called twice for each page load, which obviously is not desirable if your event-handlers are not idempotent.