范围ASP.Net变量 [英] Scope Of ASP.Net Variables

查看:93
本文介绍了范围ASP.Net变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一点一个奇怪的问题与变量的范围有关。我声明的变量通过以下方式:

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;
    }
}

和这部作品对我的网页的运作罚款。然而,当两个用户都使用相同的页面,我发现我越来越交叉。如果一个用户要的变量设置为5和其他用途则访问的变量将被设置为5.如何设置变量,它只是给谁最初设置用户访问?

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?

推荐答案

如果您声明 MyGlobalVariable 为静态的,那么就只有一个实例将存在的所有实例类,所以就像你说的,多用户,在德同一个页面的多个实例将访问相同的值。

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.

无论是申报不静态修饰符的int或者如果你需要它持续的用户,可以考虑使用视图状态(对于页面范围)或会话(用于会话范围)

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)

例如

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

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

这篇关于范围ASP.Net变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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