0

我是编程新手,这可能是一个简单的问题,但我似乎无法弄清楚。我的程序中有以下两个课程:

public class TrackingObject
{
public int OrderId { get; set; }
public int ProjectCount { get; set; }
public IList<ProjectInfo> Projects { get; set; }
}

public class ProjectInfo
{
public int ProjectId { get; set; }
public string ProjectType { get; set; }
public int ImageCount { get; set; }
}

为了测试,我创建了一个控制台应用程序并使用了以下代码:

static void Main(string[] args)
{
    TrackingObject oTracking = new TrackingObject();
    ProjectInfo pInfo = new ProjectInfo();

    oTracking.OrderId = 1;
    oTracking.ProjectCount = 1;
    pInfo.ProjectId = 1;
    pInfo.ProjectType = "CANVAS";
    pInfo.ImageCount = 1;
    oTracking.Projects.Add(pInfo);

    Console.WriteLine(oTracking.Projects.Count);
    Console.ReadLine();     
}

当我运行应用程序时,它会在以下行中引发 NullReferenceException 未处理:

    oTracking.Projects.Add(pInfo);

我足够了解该异常是因为 oTracking.Projects 为 NULL。完成我正在尝试的正确方法是什么?任何指导将不胜感激。

4

5 回答 5

5

在向其中添加oTracking.Projects = new List<ProjectInfo>()项目之前添加。

于 2013-09-05T11:49:52.533 回答
2

结合 I4V 的答案和对该答案的第一条评论:

public class TrackingObject
{
    public int OrderId { get; set; }
    public int ProjectCount { get; set; }
    public IList<ProjectInfo> Projects { get; set; }

    public TrackingObject() {
        this.Projects = new List<ProjectInfo>();
    }

    //This constructor optional, but since you're using an IList, may as well
    //let the user pass in an IList of a different type if they chose
    public TrackingObject(IList<ProjectInfo> defaultList) {
        this.Projects = defaultList;
    }
}
于 2013-09-05T11:53:56.550 回答
1

检查对象 ifnull是否分配了新实例:

if (oTracking.Projects == null) {
  oTracking.Projects = new List<ProjectInfo>();
}
于 2013-09-05T11:50:10.367 回答
0

Projects需要初始化:

 oTracking.Projects = new List<ProjectInfo>();
于 2013-09-05T11:50:02.407 回答
0
static void Main(string[] args)
{
TrackingObject oTracking = new TrackingObject();
ProjectInfo pInfo = new ProjectInfo();

oTracking.OrderId = 1;
oTracking.ProjectCount = 1;
pInfo.ProjectId = 1;
pInfo.ProjectType = "CANVAS";
pInfo.ImageCount = 1;
oTracking.Projects = new List<ProjectInfo>();
oTracking.Projects.Add(pInfo);

Console.WriteLine(oTracking.Projects.Count);
Console.ReadLine();     
}
于 2013-09-05T12:18:59.577 回答