ASP.net WebForms-构造函数与Page_Load [英] ASP.net WebForms - Constructor vs. Page_Load

查看:74
本文介绍了ASP.net WebForms-构造函数与Page_Load的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是WebForms的新手,我认为我有一个相当简单的问题.我经常看到人们在其页面类的page_load-method中初始化任何类型的依赖项.这是常事吗?

I am new to WebForms, I think I have a rather simple question. I often see people initialize any kind of dependencies in the page_load-method of their page class. Is that a common thing to do ?

我通常会在构造函数中写的东西.

Things I would usually write in the constructor.

我如何确定什么属于构造函数,什么最好放在page_load处理方法中

How do I decide what belongs in the constructor and what is better placed in the page_load handling method

推荐答案

您必须查看

You must take a look at asp.net life cycle.
On costructor method you can write lot of code, declaring variables and using classes and libraries.
But if you need some asp.net elements (Page, Controls, Session, QueryString etc) you need to be in Page_Load or in other methods of life cycle.

当ASP.NET页运行时,该页将经历生命周期,在该生命周期中它将执行一系列处理步骤.其中包括初始化,实例化控件,还原和维护状态,运行事件处理程序代码以及呈现.对您而言,了解页面生命周期很重要,这样您就可以在适当的生命周期阶段编写代码以达到预期的效果.此外,如果开发自定义控件,则必须熟悉页面生命周期才能正确初始化控件,使用视图状态数据填充控件属性以及运行任何控件行为代码.(控件的生命周期是基于页面生命周期的,但是与单个ASP.NET页面相比,该页面为控件引发的事件更多.)

When an ASP.NET page runs, the page goes through a life cycle in which it performs a series of processing steps. These include initialization, instantiating controls, restoring and maintaining state, running event handler code, and rendering. It is important for you to understand the page life cycle so that you can write code at the appropriate life-cycle stage for the effect you intend. Additionally, if you develop custom controls, you must be familiar with the page life cycle in order to correctly initialize controls, populate control properties with view-state data, and run any control behavior code. (The life cycle of a control is based on the page life cycle, but the page raises more events for a control than are available for an ASP.NET page alone.)

这篇关于ASP.net WebForms-构造函数与Page_Load的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆