字段永远不会分配给,并且将始终具有其默认值 null



我在代码中使用以下数组(注册是我的课程之一(

Enrolment[] enrolment;

我知道数组在这里没有初始化,这对错误是有意义的。但是,数组在以下代码块中初始化。

public void AddStudent(Person studentName)
    {
        try
        {
            for (int i = 0; i < enrolment.Length; i++)
            {
                if (RelevantCourse.CourseCode == null)
                {
                    throw new Exception("This section has not been added to a course.");
                }
                else if (enrolment.Length == MaxNumberOfStudents)
                {
                    throw new Exception("Cannot add this student to section. Section is full.");
                }
            }
            int currentLength = enrolment.Length;
            enrolment[currentLength] = new Enrolment(SectionId, studentName, RelevantCourse.NoOfEvaluations);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }

此代码块运行一个 try-catch 块,以查看将此Enrolment对象添加到 enrolment 数组时是否存在任何错误。enrolment数组显示一个错误,指出"字段永远不会分配给,并且将始终具有其默认值 null"。编译代码时,它显然会抛出空引用异常。

为什么它的值为空?有人可以指导我在这里找到正确的解决方案吗?

你必须初始化数组

Enrollment[] enrollments = new Enrollment[{lengthofarray}];

您无法添加内容或获取包含数组的未初始化对象的属性

最新更新