[英]NullReferenceException C# adding to dictionary
Here is a cut down snippet of the code.这是代码的精简片段。 Both tupleUnits.Key and tupleR are non-null objects. tupleUnits.Key 和 tupleR 都是非空对象。
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;
}
}
I don't understand why this is happening since both the perameters I pass into.Add() are not null.我不明白为什么会发生这种情况,因为我传入.Add() 的两个参数都不是 null。 Here are the watches:以下是手表:
- tupleUnits {[1, 3081]} System.Collections.Generic.KeyValuePair<int,int>
+ tupleR {AllLicenseeUnits.TupleRecordsRange} AllLicenseeUnits.TupleRecordsRange
Stack Trace:堆栈跟踪:
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)
In your example you haven't created the dictionary before you add to it.在您的示例中,您在添加字典之前尚未创建字典。
if (unitsInTuple == null) {
...
unitsInTuple.Add(tupleUnits.Key, tupleR);
...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.