首页 > 解决方案 > 如何解决错误“对象引用未设置为对象的实例。”

问题描述

例如。尝试添加

List<BillLineItem> BillLineItems = new List<BillLineItem>();

public void AddBillLine(BillLine billLine)
    {
        LineItems.Add(billLine);
    }

标签: c#.net.net-corec#-4.0console-application

解决方案


您收到null reference异常的原因是由于Bill课程中的这一行:

public List<BillLine> LineItems { get; set; }

它目前没有初始化列表。最简单的解决方法是:

public List<BillLine> LineItems { get; set; } = new List<BillLine>();


推荐阅读