首页 > 解决方案 > 使用类中的列表时出现 C#“未设置对象引用”错误

问题描述

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

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

(2) 我想填充一个名为“CurriculumVitae”的包装类,其中包含一个 [PersonName] 字符串和一个包含该人曾经持有的所有就业的 List 变量。我想使用循环将就业实例添加到 CurriculumVitae 的实例中,以便 CurriculumVitae 类最终在其就业列表中保存一个人的完整工作历史。

(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();
        }
    }
}

我的就业课程如下所示:

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

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

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 类中为 EmploysList 添加构造函数,但没有帮助:

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

标签: c#listclassconstructorobject-oriented-analysis

解决方案


CurriculumVitae将变量名称更改 为curriculumVitae

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

Employment_employment

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

    this.EmploymentsList.Add(employment);
}

最后你必须EmploymentsList像这样初始化version1

public List<Employment> EmploymentsList { get; set; } = new List<Employment>();

constructorversion2

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

推荐阅读