ASP Net - Difference between Page_Load and OnLoad——转载

Page_Load和OnLoad函数两者之间的区别。

Question:

Hi everybody,

sorry for the newbie question but I can't get the difference between
these two code snippets. Is it that one is a delegate (the first) and
that while the first ADDS behaviour the other completely rewrites it?

Thanks,
Lorenzo

public partial class AdminPage : Page
{
protected void Page_Load(object sender, EventArgs e){//something here}
}
---
public partial class AdminPage : Page
{
protected override void OnLoad(EventArgs e){//something here}
}

Answer 1:

You are correct. The really provide the same functionality to the code, but
only the class itself can implement OnLoad. Anything outside must use the
Load event and map it to a method. If you use the OnLoad method, you must
call the base class's OnLoad, otherwise the event handlers will not be
called.

Answer 2:

Load is the event and OnLoad is a method that raises that event when called
it's just base class implementation that does it of course, and therefore
needs to be called from deriving classes so that events work)

link: http://www.velocityreviews.com/forums/t104420-difference-between-pageload-and-onload.html

Answer 3:

The Page_Load() event handler needs to be added to the Load event of the
page class. If you're using VS.NET the IDE normally adds code that does
this for you at page init time in an override of the OnInit() method (it's
in a region of code marked with a "#region Web Form Designer generated code"
directive).

Another possible problem is that your override of the OnLoad() method is not
calling base.OnLoad() which is where the event handers registered in the
Load event will be called

link:http://www.pcreview.co.uk/forums/thread-1252089.php

 

 

重写OnLoad比Page_Load()好

首先看一下两种的代码

第一种是我们熟悉的Page_Load()方法。实际上这个是一个EventHandler,当定义再System.Web.UI.Page中的Load事件触发时,它开始执行

// use event handler
protected void Page_Load(object sender, EventArgs e)
{
//
}

 

这个是System.Web.UI.Page类中OnLoad()方法的Override。 // use override

 

protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
}

虽然上述两种做法都能完成相同的功能,但是我推荐使用Override的做法。

首先,事件处理机制是用来实现独立的对象之间通信的。例如,当一个Button被点击时,页面可以通过事件处理机制得知这一消息并进行处理。但在这 个例子中,Load事件定义在System.Web.UI.Page中,本身也是我们页面中的一部分。这样在一个类的内部发出事件并又在其本身处理这个事 件的做法将显得很奇怪。

其次,效率上考虑,事件处理不及Override。这是由.NET Framework的实现所决定的并且我们都已经了解。

还有,使用事件时需要维护两个地方:事件处理方法的加载(attach)以及事件处理函数本身的定义。虽然ASP.NET 2.0已经提供了一些预定义的事件处理方法名,但还有好多开发者在使用ASP.NET 1.1。而使用Override则只需要维护Override函数本身。

当然,事件处理机制有它自身的好处,比如可以很方便的在运行时指定事件处理方法,允许分布在各处的多个事件处理方法依次执行。但在ASP.NET页 面中我们不会用到这些特性。我们总会有一个方法来定义页面被加载的行为,我们也不会有多个Page_Load()方法在一个页面中出现。

更加泛化一点,不单单在ASP.NET页面中,其他情况下我们也应该尽可能的使用Override而不是Event。
使用Override的时候需要注意的是不要忘记调用基类的方法(Visual Studio会替你做好的)。

links:http://www.cnblogs.com/lishenglyx/articles/1291548.html

http://space.baidu.com/479775812/blog/item/edcd6d44acac6985b2b7dcd4.html

posted @ 2010-08-13 15:42  璞石攻玉  阅读(272)  评论(0编辑  收藏  举报