构造函数重载

时间:2012-01-23 18:13:24

标签: .net c#-4.0

有人能说出这里有什么问题吗?

public class Student 
{
    public List<Class> Classes { get; set; }

    public Student(List<Class> classes)
    {
       this.Classes = classes;
    }
    public Student(Class class) 
    {
        //This does not work
        //Error: Object reference not set to an instance of an object.
        this.Classes.Add(class);
    }
}

将其称为以下作品

var classes = new List<Classes>();
classes.Add(new Class("English", "Elective"));
classes.Add(new Class("Math", "Core"));
..more classes to add
Student student = new Student(classes);

当我这样打电话时(只需要添加一个课程)

Student student = new Student(new Class("Masters","Accounts"));

我收到错误。 谢谢。

4 个答案:

答案 0 :(得分:6)

Class的重载需要在添加类之前初始化类。试试这个:

public class Student 
{
    public List<Class> Classes { get; set; }

    public Student(List<Class> classes)
    {
       this.Classes = classes;
    }
    public Student(Class class) 
    {
        this.Classes = new List<Class>();
        this.Classes.Add(class);
    }
}

答案 1 :(得分:3)

在第二个构造函数中,您从未初始化Classes

答案 2 :(得分:2)

this.Classes未初始化:

public class Student 
{
    public List<Class> Classes { get; set; }

    public Student(List<Class> classes)
    {
       this.Classes = classes;
    }
    public Student(Class class) 
    {
        this.Classes = new List<Class>();
        this.Classes.Add(class);
    }
}

答案 3 :(得分:0)

在尝试向其添加对象之前,您需要初始化Classes