c# - 空对象引用

标签 c# nunit null testing

使用 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 存在并且在 block 的顶部分配了值,而 mySubReport 存在并且在行的上方分配了值 where它已添加到此报告中。 mySubReport 中的所有值都是有效的,thisReport 中的 SubReportsListSubReport 类型的通用列表。

那么,null 在哪里?看起来很简单,它一定是一些我看不到的非常明显的东西。

最佳答案

在调用 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 时调用它,这样做会实例化您的 List。

关于c# - 空对象引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3727939/

相关文章:

msbuild - 在哪里可以找到 NUnit 控制台退出代码的含义?

c# - 当我使用 VPN 连接到 SQL Server 时,如何从查询中获取 SQL Server 2008 的端口号

c# - WMI 查询太慢

c# - UWP 相当于 Timer.Elapsed 事件

c# - NUnit 3 重试测试n次

mysql - MySQL 是否索引 NULL 值?

c# - 如何最好地将字节数组从 C# 获取到 C++ WinRT 组件

nunit - 我可以围绕 NUnit、MbUnit、xUnit 或其他测试框架创建包装器吗?

java - 创建一个方法来检查不同的对象,如果 null 抛出异常

ios - 购买应用程序后,应用程序在启动时崩溃。产品标识符=无?