ICollection为什么不直接实现IEnumerator而要IEnumerable?

本人也是不得其解。还是一篇文章解决了这个问题:
The Internals ForEach

大致的意思是:为了解决嵌套循环和多线程的问题:需要一个对象来维持当前collection的current,而使得两个循环相互独立而不影响。设想一些如下代码:

 Array<string> strs = new Array<string>(3)
//initialize the array
foreach(string str in Strs)
{
   foreach(string str2 in Strs)
    {...}
 }
...

若没有IEnumerable来返回一个IEnumerator,能实现两个独立的迭代吗?
当然同样的问题存在于多线程。

其实上面的代码可以解释为:

IEnumerator e1 = (IEnumerable)strs.GetEnumerator();
while(el.MoveNext())
{
   IEnumerator e2 = (IEnumerable)strs.GetEnumerator();
   while(e2.MoveNext())
    {...}
 }

由此可见,正是由于IEnumerable.GetEnumerator()的“曲线救国”,才使得嵌套循环成为可能。
posted @ 2007-08-02 10:31  headchen  阅读(426)  评论(0编辑  收藏  举报