使用Nunit通过以下代码块测试C#代码:
foreach (XmlNode node in nodeList)
{
thisReport.Id = node.Attributes.GetNamedItem("id").Value;
thisReport.Name = node.Attributes.GetNamedItem("name").Value;
thisReport.Desc = node.Attributes.GetNamedItem("desc").Value;
if (node.SelectNodes("subreport").Count > 0)
{
thisReport.HasSubReport = true;
subReportNodeList = node.SelectNodes("subreport");
foreach(XmlNode subNode in subReportNodeList)
{
mySubReport.ParentID = node.Attributes.GetNamedItem("id").Value;
mySubReport.Priority = subNode.Attributes.GetNamedItem("priority").Value;
mySubReport.SubReportId = subNode.Attributes.GetNamedItem("id").Value;
mySubReport.SubReportName = subNode.Attributes.GetNamedItem("name").Value;
string sTime = subNode.Attributes.GetNamedItem("time").Value;
mySubReport.Time = Convert.ToInt16(sTime);
thisReport.SubReportsList.Add(mySubReport);
}
}
else
{
thisReport.HasSubReport = false;
}
reports.Add(thisReport);
}代码失败,该行上的对象引用为空:
thisReport.SubreportsList.Add(mySubReport)但是看一下本地变量,thisReport存在并且在块的顶部分配了值,而mySubReport存在并且在添加到thisReport的行正上方分配了值。mySubReport中的所有值都是有效的,并且thisReport中的SubReportsList是SubReport类型的泛型列表。
那么,null在哪里呢?它看起来如此简单,它一定是一些我看不见的明显的东西。
发布于 2010-09-16 23:03:31
在调用Add之前,您尚未实例化SubReportsList。在添加mySubReport之前,请执行以下操作
thisReport.SubReportsList = new List<SubReport>();
thisReport.SubReportsList.Add(mySubReport);您还可以更改您的SubReportsList属性以使您的工作更轻松:
public class Report
{
public IList<SubReport> SubReportsList
{
get
{
if (_subReportsList == null)
{
_subReportsList = new List<SubReport>();
}
return _subReportsList;
}
}
private IList<SubReport> _subReportsList;
}这样做将实例化您的列表,如果它在为null时被调用。
发布于 2010-09-16 23:02:18
您可能应该首先执行以下操作:
thisReport.SubReportsList = new List<SubReport>();发布于 2010-09-16 23:01:58
那么它必须是null的SubReportsList。
https://stackoverflow.com/questions/3727939
复制相似问题