zoukankan      html  css  js  c++  java
  • 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()的“曲线救国”,才使得嵌套循环成为可能。
  • 相关阅读:
    iOS
    iOS
    iOS
    iOS
    iOS
    iOS
    iOS
    iOS
    iOS
    iOS
  • 原文地址:https://www.cnblogs.com/headchen/p/839933.html
Copyright © 2011-2022 走看看