本文介绍在C#中,如何使自定义类支持foreach循环。具体步骤如下:
1、类本身实现要实现IEnumerable接口(或IEnumberable<T>泛型接口)
2、在类的内部定义一个私有的迭代器类(迭代器类当然也可以不是内嵌的私有类),迭代器类需要实现IEnumerator接口(或IEnumberator<T>泛型接口)
用图例来描述上述的工作:
下面我们就来自定义一个类StudentCollection,实现该类对foreach的支持。
实例程序类图
StudentCollection类 Student类
实例代码
Student类的代码实现:
class Student
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private int age;
public int Age
{
get { return age; }
set { age = value; }
}
private string sex;
public string Sex
{
get { return sex; }
set { sex = value; }
}
public Student() { }
public Student(string name,int age,string sex)
{
this.name = name;
this.age = age;
this.sex = sex;
}
}StudentCollection类的代码实现:class StudentCollection : IEnumerable
{
private string className;
public string ClassName
{
get { return className; }
set { className = value; }
}
public List<Student> Members = new List<Student>();
#region IEnumerable 成员
public IEnumerator GetEnumerator()
{
return new StudentCollectionEnumerator(this);
}
#endregion
private class StudentCollectionEnumerator : IEnumerator
{
private int position = -1;
private StudentCollection collection;
public StudentCollectionEnumerator(StudentCollection collection)
{
this.collection = collection;
}
#region IEnumerator 成员
public object Current
{
get { return this.collection.Members[this.position]; }
}
public bool MoveNext()
{
if (this.position < this.collection.Members.Count - 1)
{
this.position++;
return true;
}
else
{
return false;
}
}
public void Reset()
{
this.position = -1;
}
#endregion
}
}Program类的代码实现:
class Program
{
static void Main(string[] args)
{
StudentCollection students = new StudentCollection();
students.Members.Add(new Student("张三",10,"男"));
students.Members.Add(new Student("李四",11,"男"));
students.Members.Add(new Student("王五",12,"男"));
students.Members.Add(new Student("小花",10,"女"));
students.Members.Add(new Student("小丽",11,"女"));
foreach(Student student in students)
{
Console.WriteLine("学生 {0} 的信息:",student.Name);
Console.WriteLine("\t年龄:{0}",student.Age);
Console.WriteLine("\t性别:{0}\r\n",student.Sex);
}
Console.ReadLine();
}
}样例代码运行结果如下:
Word教程网 | Excel教程网 | Dreamweaver教程网 | Fireworks教程网 | PPT教程网 | FLASH教程网 | PS教程网 |
HTML教程网 | DIV CSS教程网 | FLASH AS教程网 | ACCESS教程网 | SQL SERVER教程网 | C语言教程网 | JAVASCRIPT教程网 |
ASP教程网 | ASP.NET教程网 | CorelDraw教程网 |