public class Teacher{
public string imageUrl;
public TeacherEducationalQualification[] teacherEducationalQualification;
}
public class TeacherEducationalQualification{
public string NameOfDegree;
public string NameOfUniversity;
public int YearOfGraduation;
}
在上面的代码中我实例化了像
这样的Teacher类Teacher teacher= new Teacher();
这很好但是当我在Teacher类中为对象'老师'
实例化数组时teacher.teacherEducationalQualification = new TeacherEducationalQualification[5];
它给了我一个错误'对象引用未设置为对象的实例'每当我尝试访问任何变量来设置其中的值时。
teacher.teacherEducationalQualification[1].NameOfDegree= "abc";
请帮助。
答案 0 :(得分:1)
初始化对象数组(引用类型)后,其项目将为null。您必须遍历(循环)数组并初始化每个项目。
如果你想单独设置每个项目,你可以做这样的事情
Teacher teacher = new Teacher();
teacher.teacherEducationalQualification = new TeacherEducationalQualification[5];
// Initialize item at index 0; indices start with 0 so the 1st item has index 0
teacher.teacherEducationalQualification[0] = new TeacherEducationalQualification();
teacher.teacherEducationalQualification[0].NameOfDegree= "abc";
// Initialize item at index 1
// Initialize item at index 2
// Initialize item at index 3
// Initialize item at index 4; this is the last index, your 5th item
teacher.teacherEducationalQualification[4] = new TeacherEducationalQualification();
teacher.teacherEducationalQualification[4].NameOfDegree= "xyz";
// Or in a different way with the help of a local variable
var qualification;
qualification = new TeacherEducationalQualification();
qualification.NameOfDegree= "abc";
// set other fields
teacher.teacherEducationalQualification[0] = qualification;
// ...
qualification = new TeacherEducationalQualification();
qualification.NameOfDegree= "xyz";
// set other fields
teacher.teacherEducationalQualification[4] = qualification; // last item
注意:C#中的字段名称应为camelCase - 以小写字母开头
public string nameOfDegree;
另一方面,属性应该是PascalCase - 以大写字母开头
public string NameOfDegree { get; set; } // auto-implemented property
答案 1 :(得分:1)
当您实例化一个数组时,您实际上是在创建一个能够将多个对象彼此相邻的数据结构,但是必须单独实例化对象(即数组元素)。创建数组时,将使用数组类型的默认值初始化数组的所有元素。例如,对于整数数组,所有元素都为0,对于DateTime
数组,所有元素都是DateTime.MinValue
,对于任何引用类型的数组(如上例所示),元素将为{ {1}}。这就是你得到null
的原因。如果您想使用默认构造函数实例化数组以及所有元素,可以使用以下命令:
NullReferenceException
之后,分配给每个数组元素的属性是安全的。我上面的回答并不一定意味着这是解决这个问题的最佳设计。
答案 2 :(得分:1)
在c#中实例化对象数组时,实例化一个具有空值的数组:
teacher.teacherEducationalQualification = new TeacherEducationalQualification[5];
等于
teacher.teacherEducationalQualification = new TeacherEducationalQualification[]{null, null, null, null, null};
所以
teacher.teacherEducationalQualification[1] == null
在使用之前必须实例化对象:
teacher.teacherEducationalQualification[1] = new TeacherEducationalQualification();
teacher.teacherEducationalQualification[1].NameOfDegree= "abc"
否则,如果您不想创建Object的实例,则需要使用struct:
public struct TeacherEducationalQualification{
public string NameOfDegree;
public string NameOfUniversity;
public int YearOfGraduation;
}