C#泛型类访问子类成员

来源:互联网 发布:苹果教育软件 编辑:程序博客网 时间:2024/06/15 09:29
要处理的问题是父类对象不能访问子类对象的字段。

进入正题:
有两个类,一个父类一个子类。解决的问题是要在实例化之后可以访问子类成员。
父类:
public class Student{    public string school;}
子类:
public class College:Student{    public int age;    public College(string school, int age)    {        this.school = school;        this.age = age;    }}

实例化:
        List<Student> studends = new List<Student>();        studends.Add(new College("aaa",20));           studends.Add(new College("bbb", 19));        string school = studends[0].school;           //int age = studends[0].age;  报错,不好访问子类字段        List<College> collegestudent = studends.Cast<College>().ToList();         int age = collegestudent[0].age;  //访问

定义的students是父类对象,而访问的age字段是子类字段。父类对象不能直接访问子类字段,所以要进行转换。
这里利用Cast()方法将父类集合转换成子类集合。
当然也可以用循环语句取出所有的父类对象,一个一个转。