Scope Of ASP.Net Variables

2020-06-23 13:57发布

I'm having a bit of a weird problem to do with scope of variables. I've declared a variable in the following way:

public partial class MyClass: System.Web.UI.Page
{
    protected static int MyGlobalVariable;

    protected void MyFunction()
    {
        MyGlobalVariable = 1;
    }
}

And this works fine on the workings of my page. However when two users are using the same page I'm finding that I'm getting cross over. If one user were to set the variable to 5 and the other use then accessed that variable it would be set to 5. How can I set the variable so it's only accessible to the user who originally set it?

3条回答
唯我独甜
2楼-- · 2020-06-23 14:11

Do not ever use STATIC variables in your pages.

Static variables use same memory address internally. So all users will get same value stored.

Well, if you use this in need of 'public' varilables. Then you will need to use some tricks like viewstate or session.

查看更多
\"骚年 ilove
3楼-- · 2020-06-23 14:15

If you declare MyGlobalVariable as static, then only one instance of it will exist for all instances of the class, so as you said, multiple users, on multiple instances of teh same page will be accessing the same value.

either declare the int without the static modifier or if you need it to persist for that user, consider using Viewstate (for page scope) or Session (for session scope)

e.g.

protected int MyGlobalVariable
{
    get
    {
        return ViewState["MyGlobalVariable"] != null ? Convert.ToInt32(ViewState["MyGlobalVariable"] : 0;
    }
    set
    {
        ViewState["MyGlobalVariable"] = value;
    }
}

or

protected int MyGlobalVariable
{
    get
    {
        return Session["MyGlobalVariable"] != null ? Convert.ToInt32(Session["MyGlobalVariable"] : 0;
    }
    set
    {
        Session["MyGlobalVariable"] = value;
    }
}
查看更多
贼婆χ
4楼-- · 2020-06-23 14:26

Remove the static declaration:

protected int MyGlobalVariable;

More on Static variables

查看更多
登录 后发表回答