gpt4 book ai didi

c# - 从类属性创建通用列表

转载 作者:太空宇宙 更新时间:2023-11-03 18:08:55 24 4
gpt4 key购买 nike

我正在尝试制作保存有关学生的数据的类(class),以及他的带有标记的类(class)列表。但是当我尝试添加数据进行测试时,我在“student.courses.Add(course);”处出错,即“对象引用未设置为对象的实例。”谁能告诉我哪里做错了?

static void Main(string[] args)
{
var student = new Student();
student.id = 1;
student.name = "John";
student.lastName = "K.";

var course = new Course();
course.code = 123;
course.nameOfCourse = "Course Name";
student.courses.Add(course);
}

public class Student
{
public int id { get; set; }
public string name { get; set; }
public string lastName { get; set; }
public List<Course> courses { get; set; }
}


public class Course
{
public int code { get; set; }
public string nameOfCourse { get; set; }
public int mark{ get; set; }
}

enter image description here

最佳答案

您没有初始化 courses 属性:

    var student = new Student();
student.Courses = new List<Course>();
student.Id = 1;
student.Name = "John";
student.LastName = "K.";

但最好在 Student 类中初始化它,这样会是:

public class Student
{
private List<Course> courses = new List<Course>();

public int Id { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
public List<Course> Courses
{
get
{
return courses;
}
set
{
courses = value;
}
}
}

旁注:最好用大写字母命名公共(public)属性,用小写字母命名私有(private)字段。

关于c# - 从类属性创建通用列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20329089/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com