在C#语言中提供 foreach 查询操作,foreach 大大的简化了要编写的代码,但是foreach 只能用来遍历一个可枚举的集合(enumable),可枚举的集合就是实现了System.Collections.IEnumerable接口的一个集合。
但是foreach 返回的是可枚举对象的一个只读集合,不可以通过foreach 来修改可枚举对象。
简单的一个例子:
int[] number_array = new int[] { 1,2,3,4,5,6};
foreach (int k in number_array)
{
Console.WriteLine(k);
}
int 类型,继承了IEnumerable<T> 接口,所有可以用foreach 来遍历。如果我们自己写的一个类,没有实现IEnumerable<T> 接口,用foreach 就不能进行迭代了,编译器会报错。
例如:
自己写的一个类:
class Student: IComparable<Student>
{
public Student()
{
// nothing
}
private int age;
public int Age
{
get { return this.age;}
set { this.age = value; }
}
public int CompareTo(Student other)
{
//throw new NotImplementedException();
if (this.age == other.age)
{
return 0;
}
else if (this.age < other.age)
{
return -1;
}
else
{
return 1;
}
}
}
这个类实现了 IComparable<T> 接口,但是没有实现 IEnumerable<T> 接口,不能用foreach 遍历。
下面的代码对这个没有实现 IEnumerable<T> 接口的类进行foreach 遍历结果发生编译错误。
//Student[] student=new Student[5];
//student.test();
//foreach (Student t in student)
//{
//}
下面我们将自己手动的给上面那个简单的类实现枚举器,通过foreach来遍历这个类。
在 IEnumerable接口中,包括一个GetEnumerator的方法:
IEnumerator GetEnumertor();
&nb

本文介绍了如何在C#中手动实现枚举器,以便于通过foreach语句遍历自定义类。当类未实现`IEnumerable<T>`接口时,编译器会报错。通过实现`IEnumerable<T>`接口和`IEnumerator<T>`接口,我们可以为类提供枚举功能。示例中展示了如何为一个未实现枚举接口的Student类添加枚举器,使得可以使用foreach进行遍历。
最低0.47元/天 解锁文章
1800

被折叠的 条评论
为什么被折叠?



