[英]Object reference not set to an instance of an object on adding an object to a list
[英]Silverlight adding to List<T> throws Object reference not set to an instance of an object
我在IE 8上使用Silverlight4。我为SharePoint 2010创建了一个新的Silverlight Web部件,该部件用于读取2种外部内容类型。 一个代表Code Plex的Chinook数据库中的发票,另一个代表每张发票的行。 我正在尝试使用Telerik Rad GridView控件以“主从细节”布局显示代码。 我以几种不同的方式尝试过此代码。 这里是一般描述:我有2个对象InvoiceHeader和InvoiceLine。
发票抬头包含发票行列表
public List<InvoiceLine> lines { get; set; }
我能够使它“工作”的唯一方法是使用foreach并循环遍历returnInvoices,然后使用sub foreach(var invoice in returnedInvoices)
并将每一行添加到列表中,然后将列表添加到当前列表中发票使用invoice.lines.Add(new InvoiceLine(line));
当然,问题在于我无法使用lines.Clear()
清除行,或者在所有InvoiceHeader对象中清除了所有行。 由于无法清除列表,因此每个发票在其自己的行中添加了以下发票行。 因此,我创建了一个InvoiceHeaders跟踪数组,并尝试使用它来进行tracking[x].lines.Add(new InvoiceLine(line));
然后我收到了该帖子的主题错误。 尝试将InvoiceLine添加到InvoiceHeader对象的列表时,对象引用未设置为对象的实例。 我不是真正的开发人员,因此,您能给我任何帮助,我将不胜感激。 目前,代码变得疯狂起来,为此我深表歉意。 我在下面包括了successedCallback:
void succeededCallback(object sender, ClientRequestSucceededEventArgs e)
{
this.Dispatcher.BeginInvoke(() =>
{
invoices.Clear();
invoiceLines.Clear();
int x = 0;
int y = 0;
foreach (var inv in returnedInvoices)
{
x++;
}
InvoiceHeader[] tracker = new InvoiceHeader[x];
foreach (var invoice in returnedInvoices)
{
tracker[y] = new InvoiceHeader(invoice);
//Get the lines that correspond to this invoice.
foreach (var line in returnedLines)
{
if(line.FieldValues["InvoiceId"].ToString() == invoice.FieldValues["InvoiceId"].ToString())
{
//tracker[y].lines.Add(new InvoiceLine(line));
/*
* If I comment out the line above
* I do not get the error, but I also
* don't get my detail level.
*/
}
}
invoices.Add(tracker[y]);
if (y < x) { y++; }
}
radGridView1234.ItemsSource = invoices;
}
);
}
您何时初始化lines
? 通常,集合属性在用作自动属性时仅具有带有私有设置程序的getter。
public List<InvoiceLine> lines { get; private set; }
您必须在当前调用.Add
对其进行初始化。
lines = new List<InvoiceLIne>();
我看不到您的代码示例中对lines
的引用,我无法真正遵循,但是此异常意味着您具有空引用。 像您的行声明之类的自动属性的类型的初始值为默认值,对于List来说,它的值为null,因此是繁荣。
不建议直接通过属性公开List,因为您将获得的行为很少符合您的预期,并且我建议您将其重构为非自动封装的私有和初始化字段,即:
// private field for your data
private List<InvoiceLine> _lines = new List<InvoiceLine>();
// public prop to expose it - but I'd be better still if I just exposed an Add method.
public List<InvoiceLine> Lines
{
get { return this._lines; }
}
但是对于现在的问题,最简单的方法是设置lines = new List<InvoiceLine>();
在尝试将其添加之前的某个时候-从首选项的构造函数中添加。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.