Page_Init与OnInit之间的区别 [英] difference between Page_Init vs OnInit
问题描述
一周前我接受了一次采访,其中一个问题是OnInit,Page_Init和PreRender之间的区别是什么.哪一个更可取?
Page_Init
是 Page.Init
事件的事件处理程序,如果添加类本身的处理程序.
OnInit
是引发 Init
事件的方法.
如果在子类中使用,则这两者可以看作是等效的,但是存在区别:只有 Init
暴露于其他类型, OnInit
方法受到保护,并负责引发事件,因此,如果您覆盖 OnInit
而未能调用 base.OnInit
,则 Init
事件不会被触发.看起来是这样的:
公共类页面{公共事件EventHandler Init;公共事件EventHandler加载;受保护的虚拟void OnInit(Object sender,EventArgs e){if(this.Init!= null)this.Init(sender,e);}受保护的虚拟void OnLoad(Object sender,EventArgs e){if(this.Load!= null)this.Load(发送者,e);}公共无效ExecutePageLifecylce(){this.OnInit();//在这里做些保持this.OnLoad();//进一步整理房间this.Dispose();}}公共类MyPage:页面{公共MyPage(){this.Init + = new EventHandler(MyPage_Init);}私人void MyPage_Init(Object sender,EventArgs e){//这里不需要额外的呼叫}受保护的重写void OnLoad(Object sender,EventArgs e){//您必须进行以下调用才能调用任何.Load事件处理程序base.OnLoad(sender,e);}}
通常,重写 OnLoad
/ OnInit
方法的速度更快(但这是一次微优化,您只保存了一些额外的指令用于委托分派),而且许多纯粹主义者"会认为不必要地使用事件是丑陋的:)
不使用事件的另一个优点是避免了由 AutoEventWireUp
引起的错误,该错误可能导致每次页面加载都调用两次事件,如果事件处理程序不是幂等的,显然这是不希望的./p>
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?
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.
这篇关于Page_Init与OnInit之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!