2010-08-14 33 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");