[c#]数组实例化一个对象

标签: Asp.net C#
发布时间: 2017/2/25 3:15:33
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.
public class Teacher{
    public string imageUrl;
    public TeacherEducationalQualification[] teacherEducationalQualification;
}

public class TeacherEducationalQualification{
    public string NameOfDegree;
    public string NameOfUniversity;
    public int YearOfGraduation;
}

在上面的代码时我像老师类实例化

Teacher teacher= new Teacher();

这工作正常,但当我实例化数组对象 '老师' 的老师上课

teacher.teacherEducationalQualification = new TeacherEducationalQualification[5];

每当我试图访问任何变量设置值在它,它给了我错误 '对象引用未设置到对象的实例。

teacher.teacherEducationalQualification[1].NameOfDegree= "abc";

请帮助。

解决方法 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# 中的字段名称应是驼峰匹配-以小写字母开头

public string nameOfDegree;

属性,另一方面,应将下划线-开头字母要大写

public string NameOfDegree { get; set; } // auto-implemented property
官方微信
官方QQ群
31647020