C# 类中集合引发错误的初始化

C# 类中集合引发错误的初始化,c#,list,class,exception,collections,C#,List,Class,Exception,Collections,我正在尝试访问公共集合(列表),以便在某些文本框中显示该集合中的索引对象 public partial class UpdateStudentScores : Form { int index; private StudentList students = new StudentList(); public UpdateStudentScores(int target) { InitializeComponent(); inde

我正在尝试访问公共集合(列表),以便在某些文本框中显示该集合中的索引对象

public partial class UpdateStudentScores : Form 
{
    int index;
    private StudentList students = new StudentList();

    public UpdateStudentScores(int target)
    {
        InitializeComponent();
        index = target;
    }

    private void UpdateStudentScores_Load(object sender, EventArgs e)
    {
        txtName.Text = students[index].WholeName;
    }

}
我运行程序并尝试加载数据,但在StudentList.cs中出现异常

    public Student this [int i]
    {
        get 
        {
            return students[i];
        }
        set
        {
            students[i] = value;
            Changed(this);
        }
    }
异常表示我的索引超出范围。我的学生[]里面没有任何东西。当我删除此项时:

私人学生名单学生=新学生名单()


从我的UpdateStudentScores.cs中,我不再有这种例外。我的集合的初始化如何干扰我的StudentList类的填充?

您的表单正在加载/初始化,但列表中的索引0处没有任何内容。没有代码中的任何位置将项目加载到集合中

变量
索引
是一种值类型,默认为零

txtName.Text = students[index].WholeName;

除非是数组,
列表
在创建时为空(
List.Count==0
)。必须先添加项,然后才能通过索引访问它们

public Student this [int i]
{
    get 
    {
        return students[i];
    }
    set
    {
        if (i < students.Count) {
            students[i] = value;
            Changed(this);
        } else if (i == students.Count) {
            students.Add(value);
            Changed(this);
        } else {
            throw new IndexOutOfRangeException(
                "Student at this index is not accessible.");
        }
    }
}
public Student this[int i]
{
得到
{
留学生[我];
}
设置
{
如果(i
Bingo!添加了students.Fill();它成功了。总有一天我会知道我在做什么。