c# - 如何处理 ((List<string>)Session.Add ("")

标签 c# asp.net arrays string session

((List<string>)Session["answera"]).Add(xle.InnerText); 

我需要执行此操作,但我得到“对象引用未设置为...的实例” 我不想用

 List<string> ast = new List<string>();
    ast.Add("asdas!");
    Session["stringList"] = ast;
    List<string> bst = (List<string>)Session["stringList"];

因为我只想向 Session-String-Array 添加一个字符串。

最佳答案

您是否考虑过包装您的 List<string>在自定义上下文对象的属性中?我必须在应用程序上做类似的事情,所以我最终创建了对我来说是 UserContext 的东西。对象,它有一个 Current属性,负责创建新对象并将它们存储在 session 中。这是基本代码,已调整以包含您的列表:

public class UserContext
{
    private UserContext()
    {
    }

    public static UserContext Current
    {
        get
        {
            if (HttpContext.Current.Session["UserContext"] == null)
            {
                var uc = new UserContext
                             {
                                 StringList = new List<string>()
                             };

                HttpContext.Current.Session["UserContext"] = uc;
            }

            return (UserContext) HttpContext.Current.Session["UserContext"];
        }
    }

    public List<string> StringList { get; set; }

}

我实际上从 this SO question 得到了大部分代码和结构.

因为这个类是我的 Web 的一部分命名空间,我访问它就像访问 HttpContext.Current对象,因此我永远不必显式转换任何内容。

关于c# - 如何处理 ((List<string>)Session.Add (""),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3483521/

相关文章:

c# - 从网站读取信息c#

c# - 存储过程不适用于 c# 代码

asp.net - Application_Start 和 Application_OnStart 之间的区别

javascript - 我想循环遍历数组并修改属性

c# - 从 Windows 客户端应用程序管理远程 *UNIX 服务器上的文件的方法

c# - 在单个列表中获取重复的字段名称

c# - 为什么 bytes.length = 0?

c# - 使用 Entity Framework 6 手工制作 POCO?

c - 使基于数组的程序在没有元素的情况下工作

c++ - 如何将数据存储在大型二维数组中