2010-08-14 50 views
4
((List<string>)Session["answera"]).Add(xle.InnerText); 

我需要执行此操作,但我得到“未将对象引用设置的实例......” 我不要使用如何处理((名单<string>)Session.Add(“”)

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

,我只是想将一个字符串添加到会话字符串数组。

回答

3

如果你得到一个空引用异常,这是因为无论是会议不包含像你认为的那样的列表,或者“xle”是空的。是否有任何理由认为会话已经包含了你的清单?

+0

当然,我的错。 : - /我忘了我重写了我的PageLoad并忘记检查,因为我确信它一定是别的东西。 Thx – dll32 2010-08-14 13:41:36

0

您可以使用

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

但你必须确保Session["answera"]null

或者试试这样:

string[] stringArray = {"asdas"}; 
List<string> stringList = new List<string>(stringArray); 
4

你有没有想过在一个自定义上下文对象的属性来包装一下你List<string>?我不得不在应用程序上这样做,所以我最终创建了一个UserContext对象,该对象具有Current属性,该属性负责创建新对象并将它们存储在会话中。这里是基本的代码,调整为有你的清单:

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对象那样访问它,所以我从不需要明确地施放任何东西。

+0

+1我总是将我的会话对象包装在一个静态类中,该静态类公开了类型化对象 – roosteronacid 2010-08-14 14:00:46

1

这样定义的属性,并使用属性,而不是访问Session对象

public List<string> StringList 
{ 
    get 
     { 
      if (Session["StringList"] == null) 
        Session["StringList"] = new List<string>(); 

      return Session["StringList"] as List<string>; 
     } 
} 

在任何地方你的应用程序,你只是做:

StringList.Add("test");