【问题标题】:Why i obtain this exception when I try to add an object to a list? (EX: Object reference not set to an instance of an object) [duplicate]为什么当我尝试将对象添加到列表时会出现此异常? (例如:对象引用未设置为对象的实例)[重复]
【发布时间】:2014-05-30 15:10:45
【问题描述】:

我有以下情况。在一个方法中,我有以下代码:

XmlNodeList n_vulnerablesystemslist = n_alertdocument.SelectNodes(
    "./x:VulnerableSystems/x:VulnerableSystem", nsmgr);

foreach (XmlNode n_vulnerablesystem in n_vulnerablesystemslist)
{
    DataModel.Vulnerability.VulnerableSystem currentVulnerableSystem = 
        new DataModel.Vulnerability.VulnerableSystem();

    currentVulnerableSystem.Title = 
        n_vulnerablesystem.SelectSingleNode("./x:Title", nsmgr) == null 
        ? "" 
        : n_vulnerablesystem.SelectSingleNode("./x:Title", nsmgr).InnerText;
    currentDeepSightVuln.VulnerabilityVulnerableSystems.Add(
        currentVulnerableSystem);
}

VulnerabilityVulnerableSystems 是在 Vuln currentDeepSightVuln 对象中定义的以下集合:

public virtual List<VulnerableSystem> VulnerabilityVulnerableSystems
    { get; set; }

问题是当尝试执行 Add 操作时抛出以下异常:

  • ex {“对象引用未设置为对象的实例。”} System.Exception {System.NullReferenceException}

这在我看来很奇怪,因为在调试器中我可以看到 VulnerableSystem currentVulnerableSystem 对象已初始化,并且其 Title 已正确评估。

那么问题是什么?我错过了什么?我该如何解决?

Tnx

【问题讨论】:

  • 那么有什么东西可以将VulnerabilityVulnerableSystems 设置为非空值吗?

标签: c# .net list exception


【解决方案1】:

因为列表VulnerabilityVulnerableSystems 尚未初始化。所以 Add 方法对 Null 引用进行操作。

试试VulnerabilityVulnerableSystems = new List&lt;VulnerableSystem&gt;();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-04
    • 2014-01-09
    • 1970-01-01
    • 2012-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多