理解 IEnumerable 与 IEnumerator

我们在编码中,经常使用foreach遍历集合,能够遍历的集合必定实现了 IEnumerator接口,IEnumerator接口如下:

 1 public interface IEnumerator
 2 {
 3       // 方法
 4       //移到集合的下一个元素。如果成功则返回为 true;如果超过集合结尾,则返回false。
 5       bool MoveNext();
 6      // 将集合设置为初始位置,该位置位于集合中第一个元素之前
 7       void Reset();
 8 
 9       // 属性:获取集合中的当前元素
10       object Current { get; }
11 }

要想使用foreach 遍历集合,集合必须继承 IEnumerator接口,实现IEnumerator接口中的方法。

 

而IEnumerable接口返回一个IEnumerator类型的实例,IEnumerable接口如下:

1 public interface IEnumerable
2 {
3       //IEnumerable只有一个方法,返回可循环访问集合的枚举数。
4       IEnumerator GetEnumerator() ;
5 }

为什么要这样设计呢?IEnumerable体现了做什么,IEnumerator体现了怎么做,符合软件工程中的接口隔离原则。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值