c# - 使用类中的列表时出现 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>();
}
...
}
解决方案
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>();
或constructor
在version2
public CurriculumVitae()
{
this.EmploymentsList = new List<Employment>();
}
推荐阅读
- apache - 基于查询字符串查找的 Apache httpd 重写 url
- python - 似乎无法让我的谷歌地图数据抓取工作
- c# - 将具有未定义参数类型的方法传递给另一个方法
- asp.net - 当我没有指定任何内容时,强化发现的隐藏字段
- python - 如何提高前馈神经网络的准确性?
- python-2.7 - 海龟计划在一段时间后变慢。试过清屏和删除但没有效果
- r - 有没有一种简单的方法可以让数据框看起来不错?
- node.js - 如何从猫鼬连接获取主机/端口?
- oracle - 我收到错误 ORA-06531: Reference to uninitialized collection
- javascript - 在 Angular 中删除后刷新页面