C# global.asax问题-为ASP.NET中的所有新会话提供ArrayList

C# global.asax问题-为ASP.NET中的所有新会话提供ArrayList,c#,asp.net,session,global-asax,C#,Asp.net,Session,Global Asax,我想向所有会话公开Global.asax中定义的ArrayList。下面是Global.asax和Default.aspx中的一些代码: public class Global : System.Web.HttpApplication { public ArrayList userNameList = new ArrayList(); protected void Application_Start(object sender, EventArgs e) {

我想向所有会话公开Global.asax中定义的ArrayList。下面是Global.asax和Default.aspx中的一些代码:

public class Global : System.Web.HttpApplication
{

    public ArrayList userNameList = new ArrayList();
    protected void Application_Start(object sender, EventArgs e)
    {

    }

    protected void Session_Start(object sender, EventArgs e)
    {

    }
}


public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Global global = new Global();
        User user = new User();
        user.username = TextBox1.Text;
        global.userNameList.Add(user);
        if (global.userNameList.Count != 0)
        {
            foreach (User u in global.userNameList)
            {
                ListBox1.Items.Add(String.Format(u.username));
            }
        }
    }
}

请告诉我我做错了什么。谢谢:)

您做错的第一件事是尝试在页面中实例化全局类。这不会像你期望的那样起作用

如果要在所有会话中共享ArrayList(或任何其他内容),则可能应使用应用程序状态:-


您还应该阅读有关同步访问共享状态的内容,因为可能存在潜在的线程问题,具体取决于您正在执行的操作。

删除global.asax文件中使用的任何内容,并在您的aspx页面中使用此代码

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        User user = new User();
        user.username = TextBox1.Text;


        if (Cache["userList"] == null)
            Cache["userList"] = new ArrayList();

        ((ArrayList)Cache["userList"]).Add(user);

        foreach (User u in (ArrayList)Cache["userList"])
        {
            ListBox1.Items.Add(String.Format(u.username));
        }
    }
}
确保重构您的代码,因为您很容易遇到维护问题,而且它根本不可进行单元测试。希望能有帮助


狮子座

欢迎来到SO,Krystian。欣赏代码示例。如果你也描述了你看到的问题,你可能会得到更多的帮助。