Page_Load不是虚方法.什么叫这种方法,它是如何做到的?是反射还是其他技术?还有多少事件以这种方式处理?
还是最好处理重载的OnLoad或Page_Load中的东西?他们有什么不同?
And*_*are 23
ASP.NET有一个名为"AutoEventWireup"的功能 - 此功能允许您创建具有EventHandler类似名称的签名的方法,Page_Load并且运行时将事件从父页面连接到类中的方法.基本上运行时会代表您执行此操作:
this.Load += this.Page_Load;
Run Code Online (Sandbox Code Playgroud)
现在最好禁用AutoEventWireup并在pages OnInit方法中自己创建这些事件处理程序,或者只是覆盖父页面的OnLoad方法.
编辑(响应下面的OP评论):此过程不包括按钮点击等,但过程类似.
为了使方法MyButton_Click在没有显式创建事件处理程序的情况下工作,您必须OnClick在aspx文件中的控件上设置属性,如下所示:
<asp:button
id="MyButton"
onClick="MyButton_Click"
runat="server" />
Run Code Online (Sandbox Code Playgroud)
这将提示ASP.NET为您创建按钮单击委托并将其附加到按钮的Click事件.
虚拟方法 (OnLoad) 和事件处理程序 (Page_Load) 的调用顺序由所谓的页面生命周期定义。这正是 ASP.NET 运行时处理传入请求的方式(例如,使用 Init、Load、Render 阶段)。
您可以使用 OnLoad 或 Page_Load 但您必须知道会发生什么:
如果您不在 OnLoad 重写中调用 base.OnLoad,则不会引发 Load 事件。
更新:您可以使用带有以下代码隐藏的空页面来查看会发生什么:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
base.Load += new EventHandler(My_Page_Load);
}
void My_Page_Load(object sender, EventArgs e)
{
Response.Write("My_Page_Load<br/>");
}
protected override void OnLoad(EventArgs e)
{
Response.Write("Start of OnLoad<br/>");
base.OnLoad(e);
Response.Write("End of OnLoad<br/>");
}
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("Page_Load<br/>");
}
Run Code Online (Sandbox Code Playgroud)
尝试注释 base.OnLoad(e) 调用并再次查看。
| 归档时间: |
|
| 查看次数: |
27170 次 |
| 最近记录: |