自定义迭代器使用foreach

简介:

foreach遍历集合好处很多,因为.net framework在foreach中已经做了try...catch和dispose的操作。那么如果想自定义一个集合并且该集合能使用foreach来遍历,一般做法是实现System.Collections.IEnumerable和System.Collections.IEnumerator接口。其实只要在集合类中实现无参数的返回IEnumerator的GetEnumerator方法就可以了。如下面代码

复制代码
 1 public class MyList
2 {
3 private string[] list=null;
4 public MyList(string[] sArg)
5 {
6 list = sArg;
7 }
8 public int Count{get{return list.Length;}}
9 public IEnumerator GetEnumerator()
10 {
11 return new MyListEnumerator(list);
12 }
13 }
14
15 public class MyListEnumerator:IEnumerator
16 {
17 private string[] list=null;
18 private int index=-1;
19
20 public MyListEnumerator(string[] sArg)
21 {
22 list = sArg;
23 }
24
25 public string Current{get{return list[index];}}
26 public bool MoveNext()
27 {
28 bool result = false;
29 if(index+1<list.Length)
30 {
31 ++index ;
32 result=true;
33 }
34 return result;
35 }
36 }
复制代码

这样MyList就可以通过foreach来遍历了。如果要用Linq那么MyList就要实现IEnumerable接口了。

如果您觉得本文的内容有趣就扫一下吧!捐赠互勉!


本文转自^_^肥仔John博客园博客,原文链接:http://www.cnblogs.com/fsjohnhuang/archive/2011/12/22/2297882.html,如需转载请自行联系原作者

相关文章
|
9天前
Collection和Map的遍历方式
Collection和Map的遍历方式
9 0
|
3月前
map删除迭代器的处理
map删除迭代器的处理
|
10月前
|
API
迭代器 Collection以及List接口
迭代器 Collection以及List接口
46 0
|
10月前
|
JSON 数据格式
for_forEach_map有什么区别?区别大了
for、forEach、map日常都在用,但是你知道他们有什么区别吗?为什么要有这么多功能相似的东西?性能怎么样?看这里,我告诉你
58 0
Collection.stream()forEach()和Collection.forEach()有什么区别?
Collection.stream()forEach()和Collection.forEach()有什么区别?
常见遍历方法 for循环、forEach、map、filter、find、findIndex、some、every
常见遍历方法 for循环、forEach、map、filter、find、findIndex、some、every
135 0
|
索引
forEach用法与map用法区别
forEach用法与map用法区别
147 0
|
Java 容器
使用Iterator遍历map以及list用法
使用Iterator遍历map以及list用法
141 0
使用Iterator遍历map以及list用法
【Groovy】map 集合 ( map 集合遍历 | 使用 map 集合的 find 方法遍历 map 集合 | 代码示例 )
【Groovy】map 集合 ( map 集合遍历 | 使用 map 集合的 find 方法遍历 map 集合 | 代码示例 )
343 0
【Groovy】map 集合 ( map 集合遍历 | 使用 map 集合的 find 方法遍历 map 集合 | 代码示例 )