自定义迭代器使用foreach

简介:

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


public class MyList
{
   private string[] list=null;
   public MyList(string[] sArg)
  {
     list = sArg;
  }
   public int Count{get{return list.Length;}}
   public IEnumerator GetEnumerator()
  {
     return new MyListEnumerator(list);
  }
}

public class MyListEnumerator:IEnumerator
{
   private string[] list=null;
   private int index=-1;
   
   public MyListEnumerator(string[] sArg)
   {
      list = sArg;
   }

   public string Current{get{return list[index];}}
   public bool MoveNext()
   {
      bool result = false;
      if(index+1<list.Length)
      {
         ++index ;
         result=true;
      }
      return result;
    }
}
这样MyList就可以通过foreach来遍历了。如果要用Linq那么MyList就要实现IEnumerable接口了。
目录
相关文章
|
17天前
Collection和Map的遍历方式
Collection和Map的遍历方式
10 0
|
3月前
map删除迭代器的处理
map删除迭代器的处理
|
10月前
|
API
迭代器 Collection以及List接口
迭代器 Collection以及List接口
46 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
136 0
|
索引
forEach用法与map用法区别
forEach用法与map用法区别
148 0
|
Java 容器
使用Iterator遍历map以及list用法
使用Iterator遍历map以及list用法
141 0
使用Iterator遍历map以及list用法
|
索引
forEach遍历数组对象且去重
forEach遍历数组对象 var obj1 = [{ key: '01', value: '哈哈' }, { key: '02', value: '旺旺' }, { key: '03', value: '娃娃' }, { key: '04', value: '皮皮' },...
1451 0
|
容器
你知道for、foreach和Iterator遍历有什么(效率)区别吗
1.在形式上 for的形式是for(int i=0;i
1125 0

热门文章

最新文章