很早就用过迭代器了,今天才发现它的延迟特性,汗。。。
昨天在看.Net 4.0的新特性时,看到一个枚举文件系统的新方法。
其实我很早之前就知道4.0会提供这样的方法,但我一直以为会用委托、事件或接口来实现,所以当我看到下面这段话时,很是惊讶:
File System Enumeration Improvements
New enumeration methods in the Directory and DirectoryInfo classes return IEnumerable<(Of <(T>)>) collections instead of arrays. These methods are more efficient than the array-based methods, because they do not have to allocate a (potentially large) array and you can access the first results immediately instead of waiting for the complete enumeration to occur.
该方法返回的是IEnumerable<T>,凭什么就能每得到一个文件(或目录)就能进行操作,而不是枚举完所有的才能操作呢?
通过自己的实践和网上的资料,算是了解了迭代器的延迟特性,感兴趣的朋友可以到下面的链接去看看:
不能不说的C#特性-迭代器(下),yield以及流的延迟计算