【发布时间】:2021-06-21 15:06:46
【问题描述】:
我有这样的课程:
public class myDataType
{
public class GetInvoice
{
public string InvoiceID { get; set; }
public string InvoiceNumber { get; set; }
public decimal InvoiceAmount { get; set; }
public List<InvoiceRow> Rows { get; set; }
}
public class InvoiceRow
{
public decimal RowQty { get; set; }
public string RowCode { get; set; }
public string RowDescription { get; set; }
}
}
而当我要添加数据的时候
using static test.myDataType;
...
private void LoadData()
{
GetInvoice Invoice = new GetInvoice();
Invoice.InvoiceID = "0a8625e5-62f6-4ad7-a8bf-ab04b1158392";
Invoice.InvoiceNumber = "Inv-001";
Invoice.InvoiceAmount = 100;
Invoice.Rows.Add(new InvoiceRow { RowQty= 1, RowCode = "C100", RowDescription = "Item C100"});
}
当尝试添加行时:
Invoice.Rows.Add(new InvoiceRow { RowQty= 1, RowCode = "C100", RowDescription = "项目 C100"});
显示这个错误“System.NullReferenceException: 'Object reference not set to an instance of an object'”
我想我有一个错误的方法来做这件事 有人可以帮忙吗?
提前致谢
【问题讨论】:
-
Invoice.Rows为空。在尝试添加任何新元素之前,请确保为它分配了一个List<InvoiceRow>实例,例如与public List<InvoiceRow> Rows { get; set; } = new List<InvoiceRow>()。我会将您的问题链接到另一个关于调试 NullReferenceExceptions 的好建议 -
除此之外,您可能希望
Rows属性具有private set。这仍然允许从类外更改列表,但会阻止类外的代码替换或删除您下面的列表。