开发者

Declare and create variable in code behind

开发者 https://www.devze.com 2023-01-08 21:10 出处:网络
Here are 3 scenarios: namespace NS { public partial class A: System.Web.UI.UserControl private Variable v;

Here are 3 scenarios:

namespace NS
{
    public partial class A: System.Web.UI.UserControl
    private Variable v;
    protected void Page_Load(object sender, EventArgs e){
        if (!Page.IsPostBack) v= new Variable();
        ....
    }
}

namespace NS
{
    public partial class A: System.Web.UI.UserControl
    private Variable v = new Variable();
    protected void Page_Load(object sender, EventArgs e){
    }
}

namespace NS
{
    public partial class A: System.Web.UI.UserControl
    private Variable v;
    protected void Page_Load(object sen开发者_Go百科der, EventArgs e){
        v = new Variable();
    }
}

When does the variable "v" gets created every time for the 2nd scenario? Is the 2st scenario is equivalent to the 3rd one?


Scenario 1: the variable v is intialized on every request, when page load happens, and there is no post back. (otherwise null)

scenario 2: the variable v is initialized on every instantiation of the class A, bevore the constructor is called.

scenario 3: the variable v is intialized on every request, when page load happens.

comment: if you access the variable v only after page load happens, then scenario 2 & 3 can be treated equal.


In your example the variable is always there at the same point, it is a private member of class A.

The initialization point is the difference between your example 1, 2, and 3.

In example one if there is no other calls, v will be null at all times.

In example two, v will contain a reference to a default "Variable" object as soon as class A is referenced

In example three, v will be null up until the Page_Load call then will contain a reference to a default 'Variable' object after that.


"It is created when the Page object is created which must occur before any events or methods of the object can be called." and "Sort-of. The creation is delayed a bit longer in the 3rd"

0

精彩评论

暂无评论...
验证码 换一张
取 消