果然最近上的继承有点复杂了。 定义了父类 Student: public class Student { private string _id; private string _name; private bool _gender; private int _class; private int _grade; #region//属性 //有属性ID,Name,Gender,Class,Grade #endregion //构造函数 public Student(string id, string name, bool gender, int _class = 1, int grade = 1) { this._id = id; this._name = name; this._gender = gender; this._class = _class; this._grade = grade; } public new string ToString() { return _id + _name; } } 然后加了两个子类Undergraduate和Graduate,分别多了string类型的属性Department和Tutor students = new Student[5]; students[0] = new Student("1001", "赵华", false); students[1] = new Student("1002", "彭小飞", true, 3); students[2] = new Undergraduate("1003", "王萌", false, 1, 4) { Department = "计算机" }; students[3] = new Student("1004", "王小明", true, 2, 3); students[4] = new Undergraduate("1005", "张珊", false, 1, 3) { Department = "英语" }; 如上,是不是表示students[2]和student[4]的实际类型为父类Student,而不是子类Undergraduate?? 然后实现StudentForm窗口的加载事件时,不能直接调用子类的Department属性,强制转化则运行后异常。 附StudentForm的构造函数代码: private Student student; public StudentForm(Student student) { this.student = student; InitializeComponent(); } 和Load事件中的代码: textBoxDe.Text = student.Department; //此写法报错 textBoxDe.Text = ((Undergraduate)student).Department; //此写法异常 |
|
20分 |
实际类型是Undergraduate,但是可以通过Student类型的引用 使用变量 |
20分 |
第一行报错是正常的,没法通过parent class的引用 访问sub class的成员。 第二行没有问题,如果student真的是一个undergraduate类型的话,一般都要先判断一下。 Undergraduate undergraduateStudent = student as Undergraduate |