AutoEventWireup and base.OnLoad(e) Calling Self resulting in Stack Overflow

老子叫甜甜 提交于 2019-12-22 08:34:16

问题


Using VS2008, C#. When AutoEventWireup is set to true and in a webform I call base.OnLoad(e) like:

protected void Page_Load(object sender, EventArgs e)
{
    base.OnLoad(e);
}

The base.OnLoad(e) ends up calling Page_Load (calls itself). This ends up with a stack overflow error. I've been able to solve it by setting AutoEventWireup to false and overriding OnLoad:

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

This works as I expected (no stack overflows). But can anyone explain why in the first example base.OnLoad(e) calls the same load event (calls itself) rather than calling the OnLoad event in the base class (System.Web.UI.Page)?


回答1:


OnLoad doesn't call itself, it calls the Load event. The Page.OnLoad method merely wraps the call to the attached events. You should not call base.OnLoad from a Load event handler or it will result in an infinite loop.




回答2:


Page.OnLoad has the following pseudo-code inside it

protected virtual void OnLoad() {
    // some stuff

    if (Load != null)
        Load(this, new EventArgs());
}

if you override the OnLoad function, what happens is: Your OnLoad happens, then it calls base.OnLoad(), and that calls the (empty) Load event.

If you implement the Load event and call base.OnLoad(), this is what happens: base.OnLoad() calls the Load event. The Load event then calls base.OnLoad(). Then, base.OnLoad() calls the Load event. And the rest is, as they say, to understand recursion you must first understand recursion.

Hope I made myself clear.



来源:https://stackoverflow.com/questions/563594/autoeventwireup-and-base-onloade-calling-self-resulting-in-stack-overflow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!