我是编程新手,这可能是一个简单的问题,但我似乎无法弄明白。我的课程中有以下两个课程:
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。完成我的尝试的正确方法是什么?任何指导都将非常感激。
答案 0 :(得分:5)
在向其添加项目之前添加oTracking.Projects = new List<ProjectInfo>()
。
答案 1 :(得分: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;
}
}
答案 2 :(得分:1)
检查对象是否null
,如果它是指定新实例:
if (oTracking.Projects == null) {
oTracking.Projects = new List<ProjectInfo>();
}
答案 3 :(得分:0)
Projects
需要初始化:
oTracking.Projects = new List<ProjectInfo>();
答案 4 :(得分: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();
}