从classproperties创建通用列表

时间:2013-12-02 13:06:06

标签: c# .net

我正在尝试制作关于学生数据的课程,并且他的课程列表带有标记。但是,当我尝试添加测试数据时,我在“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

4 个答案:

答案 0 :(得分:4)

您尚未初始化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;
       }
    }
}

旁注:最好使用大写字母和私有字段命名公共属性。

答案 1 :(得分:2)

您正在尝试调用方法添加空值(即student.courses)。 尝试将代码重新设计成类似的东西:

public class Student
{
    // Courses are always exist, but list may be empty
    private List<Course> m_Courses = new List<Course>();

    public int id { get; set; }
    public string name { get; set; }
    public string lastName { get; set; }

    // There's IMHO no need in set accessor 
    // (lack of "set" is a good thing to prevent "student.courses = null;" code)
    public List<Course> courses { 
      get {
        return m_Courses;
      } 
    }
}

答案 2 :(得分:1)

list中的课程Student永远不会被初始化。使用代码修复此问题的最简单方法是编写类Student,如下所示:

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 Student()
    {
        courses = new List<Course>();
    }
}

像这样,您可以忘记在创建Student的实例后必须初始化课程。否则,您必须手动对所创建的每个实例执行此操作,如下所示:

var student = new Student();
student.courses = new List<Course>();

答案 3 :(得分:1)

您正在初始化student,但由于您未初始化courses属性,因此默认为null,因为它是引用类型。 (List<Course>

student.courses = new List<Course>();
相关问题