1: 当T为简单类型
List<int> list = new List<int>(); list.Add(1); list.Add(2); foreach (var va in list) //使用 foreach 语句 { Console.WriteLine(va); } for (int i = 0; i < list.Count; i++) //使用 for 语句 { Console.WriteLine(list[i]); }
结果:
2:当 T 为对象
namespace fanxing { class Program { static void Main(string[] args) { List<Student> stu = new List<Student>(); stu.Add(new Student("jack", 14)); // 将对象加入到泛型集合中 stu.Add(new Student("jely", 15)); foreach (Student s in stu) { Console.WriteLine("{0},{1}", ((Student)s).StudentName, ((Student)s).Age); // 先将 集合s 转为 类类型Student, 然后获取其属性值 } for (int i = 0; i < stu.Count; i++) { Console.WriteLine("{0},{1}", ((Student)stu[i]).StudentName, ((Student)stu[i]).Age); } } public class Student { private string studentName; private int age; public string StudentName { get { return studentName; //一定要有这句 } } public int Age { get { return age; } } public Student(string sStudentName,int aAge) { this.studentName = sStudentName; this.age = aAge; } } } }
从泛型集合中取出元素时不再需要进行拆箱操作(或显示类型转换)
所以可以直接将两个输出改为(效果一样):
foreach (Student dent in stu) { Console.WriteLine(dent.StudentName); } for (int i = 0; i < stu.Count; i++) { Console.WriteLine(stu[i].StudentName); }
结果: