c# - 为什么我不能将此对象添加到此列表中?

标签 c#

我是 C# 的新手,在尝试将对象插入集合时遇到以下问题。

所以我有一个名为 VulnSmall 的基类,其中包含一些属性,然后我有一个名为 Vuln 的类,该类扩展之前的 >VulnSmall 类添加了一些属性,包括名为 VulnerabilityReferences 的列表,如您在以下代码片段中所见:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataModel.Vulnerability
{
    public class Vuln : VulnSmall
    {
        .......................
        .......................
        .......................
        public virtual List<VulnerabilityReference> VulnerabilityReferences { get; set; }    

        .......................
        .......................
        .......................

    }
}

好的,

在另一个类(class)我有类似的东西:

DataModel.Vulnerability.Vuln currentNVDVuln = new DataModel.Vulnerability.Vuln();

// Creation of the VulnerabilityReference object and initialization of its fields:
DataModel.Vulnerability.VulnerabilityReference currentVulnRef = new DataModel.Vulnerability.VulnerabilityReference();

currentVulnRef.Title = "My Title";
currentVulnRef.Description = "My Descripion"
currentVulnRef.URL = "www.myurl.com"

// Adding the previous obkect to the VulnerabilityReferences list field:
currentNVDVuln.VulnerabilityReferences.Add(currentVulnRef);

如您所见,我有一个名为 currentNVDVuln 的 Vuln 对象(包含 VulnerabilityReferences 列表作为其字段),我创建了一个 VulnerabilityReference对象(名为 currentVulnRef),我尝试将其添加到此列表中。

但是不工作,当尝试执行这一行时:

currentNVDVuln.VulnerabilityReferences.Add(currentVulnRef);

它会出错并抛出这个异常:

{"Object reference not set to an instance of an object."} System.Exception {System.NullReferenceException}

为什么?可能是什么问题呢?我错过了什么?

最佳答案

您没有初始化 VulnerabilityReferences 列表。因此它具有 null 值,当您尝试调用其 Add 方法时它会抛出异常。您可以在 Vuln 类的构造函数中创建新列表:

public class Vuln : VulnSmall
{
    public Vuln()
    {
        VulnerabilityReferences = new List<VulnerabilityReference>();
    }

    // ...
}

来自 C# 规范 10.4.4 Field initialization (使用自动实现的属性你仍然有字段,但它是由编译器为你生成的):

The initial value of a field, whether it be a static field or an instance field, is the default value (Section 5.2) of the field's type.

List 是引用类型,因此默认情况下它的值为 null

关于c# - 为什么我不能将此对象添加到此列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22094532/

相关文章:

c# - 所有的逻辑应该写在 Controller 里面?

c# - SignalR - 从集线器外部通过另一个项目中的集线器广播

c# 将表单添加到项目: Possible to make it internal/private from designer?

c# - .net 请求浏览器版本不一致

c# - 如何调用默认方法而不是具体实现

c# - iTextSharp:横向表格

c# - 如何在 C# 中用单个空格替换多个空格?

c# - 从 List<KeyValuePair<string,string>> 返回匹配项

c# - Unity - 为我的按钮添加延迟

c# - 将类型转换为通用约束 T