实现Foreach遍历

时间:2023-03-08 21:38:55

实现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 = ;
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 * ];
//将原来的数组中的数据拷贝到新数组中.
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 = -; 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 = -;
}
}
}

客户端代码

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>();
list.Add(new Student() {Age=,Name="" });
list.Add(new Student() { Age = , Name = "" });
list.Add(new Student() { Age = , Name = "" });
list.Add(new Student() { Age = , Name = "" });
list.Add(new Student() { Age = , Name = "" });
list.Add(new Student() { Age = , Name = "" }); foreach (var s in list)
{
Console.WriteLine(s.Name+":"+ s.Age); } ListForeach<Student> list1 = new ListForeach<Student>() {
new Student(){ Age=,Name="yjq"},
new Student(){ Age=,Name="dddd"},
new Student(){ Age=,Name="ddd"},
new Student(){ Age=,Name="==="},
}; foreach (var s in list1)
{
Console.WriteLine(s.Name + ":" + s.Age); } Console.Write(list.Count);
Console.Read(); }
}
}