Page_Init vs OnInit

后端 未结 6 535
日久生厌
日久生厌 2020-12-08 07:40

Between handling the Page_Init event or overriding the OnInit method of a Page, which one is better to use? Thanks.

6条回答
  •  [愿得一人]
    2020-12-08 07:46

    Basically there is no difference in this two appoaches. That's what is done in OnInit in Page class:

    protected internal override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        if (this._theme != null)
        {
            this._theme.SetStyleSheet();
        }
        if (this._styleSheet != null)
        {
            this._styleSheet.SetStyleSheet();
        }
    }
    

    If we will open base.OnInit we will se that that is the place where Page_Init is fired:

    protected internal virtual void OnInit(EventArgs e)
    {
        if (this.HasEvents())
        {
            EventHandler handler = this._occasionalFields.Events[EventInit] as EventHandler;
            if (handler != null)
            {
                handler(this, e);
            }
        }
    }
    

    So basically there is no difference in these two approaches. However you need to call base.OnInit in your overriden method if you will choose to use override instead of event. And another difference is that if you are using override you can run some code just after Theme is applied.

    Regards.

    P.S. The only thing I recommend is to use the same approach all over the application.

提交回复
热议问题