实现Foreach遍历的集合类,需要实现IEnumerable接口,泛型集合则需要实现IEnumerable<T>接口
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace Foreach { public class ListForeach<T> :IEnumerable<T> where T :class ,new() { private T[] array; private int index = 0; public ListForeach(int capcity) { array = new T[capcity]; } public int Count { get { return index; } } public void Add(T value) { if (index >= array.Length) { T[] newArr = new T[array.Length * 2]; //将原来的数组中的数据拷贝到新数组中. Array.Copy(array, newArr, array.Length); //然后将旧数组的变量指向新数组 array = newArr; } array[index++] = value; } public IEnumerator<T> GetEnumerator() { return new TEnumeratro<T>(array, index); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public class TEnumeratro<T> : IEnumerator<T> { private T [] arr ; private int count; private int position = -1; public TEnumeratro(T [] array, int count) { this.arr = array; this.count = count; } public T Current { get { return arr[position]; } } public void Dispose() { arr = null; } object IEnumerator.Current { get { return this.Current; } } public bool MoveNext() { position++; if (position < this.count) return true; else return false; } public void Reset() { this.position = -1; } } }
客户端代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Foreach { public class Student { public int Age {get;set; } public string Name { get; set; } } class Program { static void Main(string[] args) { ListForeach<Student> list = new ListForeach<Student>(10); list.Add(new Student() {Age=111,Name="123" }); list.Add(new Student() { Age = 222, Name = "222" }); list.Add(new Student() { Age = 333, Name = "111" }); list.Add(new Student() { Age = 444, Name = "23222" }); list.Add(new Student() { Age = 22552, Name = "32" }); list.Add(new Student() { Age = 222, Name = "1111334" }); foreach (var s in list) { Console.WriteLine(s.Name+":"+ s.Age); } ListForeach<Student> list1 = new ListForeach<Student>(10) { new Student(){ Age=666,Name="yjq"}, new Student(){ Age=88,Name="dddd"}, new Student(){ Age=999,Name="ddd"}, new Student(){ Age=000,Name="==="}, }; foreach (var s in list1) { Console.WriteLine(s.Name + ":" + s.Age); } Console.Write(list.Count); Console.Read(); } } }