1、泛型是一种特殊的类型。泛型无须类型的转换操作。
2、泛型可以保证类型安全。泛型集合对它所存储的对象做了类型约束,不是它所允许存储的类型是无法添加到泛型集合中的。
private void btnMyClassTest_Click(object sender, EventArgs e)
{
List<Student> students = new List<Student>(); Student scofield = new Student("Scofield", Genders.Male, 28, "越狱狱");
Student zhang = new Student("张靓靓", Genders.Female, 20, "唱歌歌");
Student jay = new Student("周杰杰", Genders.Male, 21, "耍双节棍棍");
Teacher jacky = new Teacher("成龙龙", 4); students.Add(scofield);
students.Add(zhang);
students.Add(jay);
//students.Add(jacky); //编译时立即报错 //打印集合数目
MessageBox.Show(string.Format("班级 共包括 {0} 个成员。",
students.Count.ToString())); foreach (Student stu in students)
{
Console.WriteLine(stu.Name);
}
} |