您的位置:首页 > 其它

IEnumerable和IEnumerator

2016-06-13 14:24 323 查看
其实IEnumerable接口是非常的简单,只包含一个抽象的方法GetEnumerator(),它返回一个可用于循环访问集合的IEnumerator对象。IEnumerator对象有什么呢?它是一个真正的集合访问器,没有它,就不能使用foreach语句遍历集合或数组,因为只有IEnumerator对象才能访问集合中的项,假如连集合中的项都访问不了,那么进行集合的循环遍历是不可能的事情了。那么让我们看看IEnumerator接口有定义了什么东西。看下图我们知道IEnumerator接口定义了一个Current属性,MoveNext和Reset两个方法,这是多么的简约。既然IEnumerator对象时一个访问器,那至少应该有一个Current属性,来获取当前集合中的项吧。

MoveNext方法只是将游标的内部位置向前移动(就是移到一下个元素而已),要想进行循环遍历,不向前移动一下怎么行呢?

IEnumerable的定义:

public interface IEnumerable
{
// 摘要:
//     返回一个循环访问集合的枚举数。
//
// 返回结果:
//     一个可用于循环访问集合的 System.Collections.IEnumerator 对象。
[DispId(-4)]
IEnumerator GetEnumerator();
}

IEnumerator的定义:

namespace System.Collections
{
// 摘要:
// 支持对非泛型集合的简单迭代。
[ComVisible(true)]
[Guid("496B0ABF-CDEE-11d3-88E8-00902754C43A")]
public interface IEnumerator
{
// 摘要:
// 获取集合中的当前元素。
//
// 返回结果:
// 集合中的当前元素。
object Current { get; }

// 摘要:
// 将枚举数推进到集合的下一个元素。
//
// 返回结果:
// 如果枚举数成功地推进到下一个元素,则为 true;如果枚举数越过集合的结尾,则为 false。
//
// 异常:
// System.InvalidOperationException:
// 在创建了枚举数后集合被修改了。
bool MoveNext();
//
// 摘要:
// 将枚举数设置为其初始位置,该位置位于集合中第一个元素之前。
//
// 异常:
// System.InvalidOperationException:
// 在创建了枚举数后集合被修改了。
void Reset();
}
}

下面是一个简单的Demo
定义Car类class Car
{
public string CarName;
public int CarAge;
public Car(string name,int age)
{
CarName = name;
CarAge = age;
}
}定义Garage类
class Garage:IEnumerable
{
Car[] carArray=new Car[4];//定义为Car类型的carArry数组
public Garage()
{
carArray[0] = new Car("jj", 23);
carArray[1] = new Car("qq", 44);
carArray[2] = new Car("ss", 12);
carArray[3] = new Car("ff", 43);
}
public IEnumerator GetEnumerator()
{
return this.carArray.GetEnumerator();
}
}

运行程序
namespace IEnum
{
class Program
{
static void Main(string[] args)
{
Garage garage = new Garage();
foreach (Car c in garage)
{
Console.WriteLine("{0}已经{1}岁了", c.CarName, c.CarAge);
}
Console.ReadLine();
}
}
}

这个是定义了类的集合(Car类的集合),只有Garage类继承了IEnumerable的接口,才能读取和获取定义为Car类型的carArry数组.

更多了解点击阅读点击打开链接
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: