如何更正以下代码中的NullReferenceException
本文关键字:NullReferenceException 代码 何更正 | 更新日期: 2023-09-27 18:30:13
我是编程新手,这可能是一个简单的问题,但我似乎无法解决。我的程序中有以下两个课程:
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。实现我正在尝试的目标的正确方法是什么?任何指导都将不胜感激。
在添加项目之前添加oTracking.Projects = new List<ProjectInfo>()
。
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;
}
}
检查对象是否为null
,是否分配了一个新实例:
if (oTracking.Projects == null) {
oTracking.Projects = new List<ProjectInfo>();
}
Projects
需要初始化:
oTracking.Projects = new List<ProjectInfo>();
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();
}