在类中创建方法以更新类中保存的列表

时间:2013-11-26 16:37:13

标签: c# list class methods

我正在尝试在名为“顾问”的班级中创建一个列表,该班级将包含由1个顾问实例建议的学生列表。我创建了一个学生班,并且没有遇到任何麻烦,但是我的顾问班在运行时遇到了错误。

class Advisers
{
    private string _Fname;
    private string _Lname;
    private string _Department;
    private List<Student> _StudentsAdvised;   

    //constructor
    public Advisers()
    {
        _Fname = "";
        _Lname = "";
        _Department = "";
        _StudentsAdvised = null;
    }

    public void AddToList(Student newStudent)
    {
        _StudentsAdvised.Add(newStudent);
    }

    public List<Student> StudentsAdvised
    {
        get { return _StudentsAdvised; }
        set { _StudentsAdvised = value; }
    }

    public string FirstName
    {
        get { return _Fname; }
        set { _Fname = value; }
    }

    public string LastName
    {
        get { return _Lname; }
        set { _Lname = value; }
    }

    public string Department
    {
        get { return _Department; }
        set { _Department = value; }
    }       
}

我在主窗体中调用AddToList方法,将学生的实例添加到Adviser类中保存的StudentsAdvised列表中。

private void stuAssignAdviBtn_Click(object sender, EventArgs e)
    {
        int stuIndex = stuLstbox.SelectedIndex;
        int advIndex = adviListBox.SelectedIndex;

        if (stuLstbox.SelectedIndex != -1 && adviListBox.SelectedIndex != -1)
        {
            string AdvLastName = AdviserList[advIndex].LastName;
            StudentList[stuIndex].AdviserLastName = AdvLastName;


            AdviserList[advIndex].AddToList(StudentList[stuIndex]);
        }
        else
        {
            MessageBox.Show("Select 1 student and 1 adviser.");
        }
    }

错误消息出现在Adviser类中:

public void AddToList(Student newStudent)
{
    _StudentsAdvised.Add(newStudent);
}

我该怎么做?

2 个答案:

答案 0 :(得分:2)

我没有看到您在任何地方初始化List<Student> _StudentsAdvised

可以在类构造函数

中执行此操作
//constructor
public Advisers()
{
    _Fname = "";
    _Lname = "";
    _Department = "";
    _StudentsAdvised = new List<Student>();
}

答案 1 :(得分:0)

ERM,

public class Advisess : List<Student>
{
    private readonly Advisor advisor;

    private Advisess()
    {
    }

    public (IEnumerable<Student> adivsees, Advisor advisor)
        : base(advisees)
    {
        this.advisor = advisor;
    }

    public (Advisor advisor)
    {
        this.advisor = advisor;
    }

    public Advisor Advisor
    {
        get
        {
            return this.advisor;
        }
    }
}