在 class 中处理列表时出现 C# 'Object reference not set' 错误

C# 'Object reference not set' error when working with lists within a class

这对专业人士来说非常简单 - 但我自己现在已经在上面浪费了几个小时。这是我正在尝试做的事情的简化版本:

(1) 我有一个 'Employment' class 可以存储 3 个字符串 [EmployerName]、[JobTitle] 和 [PeriodOfEmployment]。我成功地创建了一个 Employment 实例并用示例条目填充它。

(2) 我想填充一个名为 'CurriculumVitae' 的包装器 class,它包含一个 [PersonName] 字符串和一个列表变量,其中包含此人曾经拥有的所有就业机会。我想使用一个循环将 Employment 的实例添加到 CurriculumVitae 的实例中,这样 CurriculumVitae class 最终会在其 EmploymentsList 中保存一个人的完整工作经历。

(3) 在 Visual Studio 中收到错误消息:

System.NullReferenceException: 'Object reference not set to an instance of an object.'
CurriculumVitae.EmploymentsList.get returned null.'.

我的简化代码是:

using System;
using System.Collections.Generic;

namespace CurriculumVitaeExample
{
    class Program
    {
        static void Main(string[] args)
        {
            var CurriculumVitae = new CurriculumVitae();
            CurriculumVitae.Open();
        }
    }
}

我的工作 class 看起来像这样:

public class Employment
{
    public string EmployerName { get; set; }
    public string JobTitle { get; set; }
    public string PeriodOfEmployment { get; set; }
}

我的 CurriculumVitae class 尝试使用列表中的就业 class,如下所示:

public class CurriculumVitae //(version 1)
{
    public string PersonName { get; set; }
    public List<Employment> EmploymentsList { get; set; }

    // Open method:
    public void Open()
    {
        Employment Employment = new Employment();

        Employment.EmployerName = "McDonalds";
        Employment.JobTitle = "Ice Cream Guru";
        Employment.PeriodOfEmployment = "Jan 2019 - Present";

        this.EmploymentsList.Add(Employment);
    }

}

我还尝试在 CurriculumVitae class 中为 EmploymentsList 添加构造函数,但没有帮助:

public class CurriculumVitae //(version 2)
{
        // Constructor:
        public CurriculumVitae()
        {
            List<Employment> EmploymentsList = new List<Employment>();
        }
        ...
}

CurriculumVitae 变量的名称更改为 curriculumVitae

static void Main(string[] args)
{
    var curriculumVitae = new CurriculumVitae();
    curriculumVitae.Open();
}

Employmentemployment

public void Open()
{
    Employment employment = new Employment();
    employment.EmployerName = "McDonalds";
    employment.JobTitle = "Ice Cream Guru";
    employment.PeriodOfEmployment = "Jan 2019 - Present";

    this.EmploymentsList.Add(employment);
}

最后你必须在 version1

中像这样初始化 EmploymentsList
public List<Employment> EmploymentsList { get; set; } = new List<Employment>();

constructorversion2

public CurriculumVitae()
{
    this.EmploymentsList = new List<Employment>();
}