2012-07-09 47 views
0

我正在努力尋找解決此問題的方法。我在本網站上看到很多涉及此主題的相似條目,但我似乎無法得出解決方案。我正在檢查緩存中的表以查看它是否已經存在,如果沒有,請填充它。下面是我的檢查代碼,它在'if'語句中的錯誤告訴我'System.NullReferenceException:對象引用未設置爲對象的實例'。這是令人費解的,因爲不應該'.IsNullOrEmpty'抓住這個?我想,如果數組中的第一個元素爲null或空,那麼它尚未被緩存,因此採取行動。數組檢查:未將對象引用設置爲對象的實例

  string[] saveCatList = Cache["Categories" + Session["sessopnID"]] as string[]; 
      if (string.IsNullOrEmpty(saveCatList[0])) 
      { 
       WBDEMOReference.getcatlist_itemcategories[] categories; 
       strResult = callWebServ.getcatlist(Session["sessionID"].ToString(), 
          out strResultText, out dNumOfCat, out categories); 

       for (int i = 0; i < categories.Length; i++) 
       { 
        //ddCat is the ID number of the category drop down list 
        ddCat.Items.Add(new ListItem(categories[i].categorydesc.ToString(), 
               categories[i].categorynumber.ToString())); 
       } 
      } 
+0

謝謝您的解答!很高興知道該數組本身是在查看其中的元素之前進行檢查的。我仍然擁有舊的COBOL;) – 2012-07-09 17:29:17

回答

5

With string.IsNullOrEmpty(saveCatList[0])您檢查數組的第一個元素是否爲空或空。看來你的數組爲null,所以你應該首先檢查你的陣列:

if(saveCatList == null || string.IsNullOrEmpty(saveCatList[0])) 
1
Cache["Categories" + Session["sessopnID"]] as string[]; 

該石膏失敗,「作爲字符串」的返回null。因此,當您嘗試以數組的形式訪問關聯的變量時,您基本上正在執行null [0],這是一個NullReferenceException。

如果您添加一個檢查以確保數組不爲空,這將工作正常。

0

變化

if (string.IsNullOrEmpty(saveCatList[0])) 

if (saveCatList != null && saveCatList.Length>0 && string.IsNullOrEmpty(saveCatList[0])) 

另外,更改

ddCat.Items.Add(new ListItem(categories[i].categorydesc.ToString(), 
              categories[i].categorynumber.ToString())); 

if (categories[i].categorydesc != null && categories[i].categorynumber!= null) 
{ 
    ddCat.Items.Add(new ListItem(categories[i].categorydesc.ToString(), 
              categories[i].categorynumber.ToString())); 

} 
相關問題