2011-07-18 88 views
0

以下是代碼的精簡片段。 tupleUnits.Key和tupleR都是非空對象。NullReferenceException將C#添加到字典中

public partial class AllLicenseeUnits : System.Web.UI.Page { 
    protected Dictionary<int, TupleRecordsRange> unitsInTuple = new Dictionary<int, TupleRecordsRange>(); 

    public Paginator getPaginator(int itemsPerPage) { 
    if (unitsInTuple == null) { 
     Dictionary<int, int> tuplesUnits = DataAccess.CountLicenseeUnitsTuple(Session["licensee"] as Licensee); 
     tuplesUnits = tuplesUnits.Where(item => item.Value > 0).ToDictionary(item => item.Key, item => item.Value); 
     int index = 0; 
     foreach(KeyValuePair<int, int> tupleUnits in tuplesUnits) { 
      TupleRecordsRange tupleR = new TupleRecordsRange{start_index = index, end_index= (index + tupleUnits.Value -1)}; 
      unitsInTuple.Add(tupleUnits.Key, tupleR); 
      index += tupleUnits.Value; 
     } 
    } 
    int sumUnits = unitsInTuple.Sum(item => item.Value.totalRecords); 
    Paginator paginator = new Paginator(itemsPerPage, sumUnits); 
    if (Request.QueryString["page"] != null) 
    { 
     paginator.currentPage = int.Parse(Request.QueryString["page"]); 
    } 
    return paginator; 
    } 
} 

我不明白爲什麼會發生這種情況,因爲兩個參數傳入.Add()不爲空。 這裏有手錶:

-  tupleUnits {[1, 3081]} System.Collections.Generic.KeyValuePair<int,int> 

+  tupleR {AllLicenseeUnits.TupleRecordsRange} AllLicenseeUnits.TupleRecordsRange 

堆棧跟蹤:

at AllLicenseeUnits.getPaginator(Int32 itemsPerPage) in C:\Users\User\Documents\Bla_Devel\AllLicenseeUnits.aspx.cs:line 46 
    at AllLicenseeUnits.Page_Load(Object sender, EventArgs e) in C:\Users\User\Documents\Bla_Devel\AllLicenseeUnits.aspx.cs:line 32 
    at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) 
    at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) 
    at System.Web.UI.Control.OnLoad(EventArgs e) 
    at System.Web.UI.Control.LoadRecursive() 
    at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) 
+0

「tuplesUnits」究竟是什麼? –

+0

什麼是堆棧跟蹤? – SLaks

+0

@Jeff它是一個詞典。我在上面添加了更多的代碼。 – Keyo

回答

3

在你加入之前,您尚未創建字典的例子。

if (unitsInTuple == null) { 
      ... 
      unitsInTuple.Add(tupleUnits.Key, tupleR); 
      ... 
     } 
    } 
+0

UnitsInTuple創建在第二行。 – MGZero

+0

謝謝,我已經意識到分配一個新的對象到unitsInTuple它從類範圍沒有實際上做任何事情。我從它的工作方法中分配了它,至少這是我的理解 – Keyo

+0

它應該從您發佈的示例中初始化 - 我的猜測是它在類中的其他地方被設置爲空 – saus