简体   繁体   English

真正的集合枚举器是如何实现的?

[英]How real enumerator for collection is implemented?

There is an example how enumerator migh be implemented: http://msdn.microsoft.com/en-us/library/system.collections.ienumerator.aspx and this is a valid approach. 有一个例子枚举如何migh实现: http://msdn.microsoft.com/en-us/library/system.collections.ienumerator.aspx ,这是一种有效的方法。 However real List or Array invalidate their iterators when they are modified. 但是,实际的ListArray在被修改时会使它们的迭代器无效。

And my question is -- how is it done? 我的问题是-如何完成?

The best I can think of is still keeping the reference to the collection, and also some stamp (int id). 我能想到的最好的方法仍然是保留对馆藏的引用,以及一些标记(int id)。 Every time the collection is resized, the stamp is incremented. 每次调整集合大小时,标记都会增加。 And on every moveNext at enumerator side, the stamp is checked -- when there is a match, enumeration continues, if not -- exception is thrown. 并在枚举器端的每个moveNext上检查图章-如果存在匹配项,则继续枚举,如果不匹配,则抛出异常。

But this is just my wild guess, I didn't find anything solid. 但这只是我的wild测,我没有发现任何可靠的方法。

how is it done? 怎么做?

Trivial. 不重要的。 Keep a version counter. 保留版本计数器。 Compare version counter when the enumerator was created to the one currently in the enumerated object on every yield. 将创建枚举器时的版本计数器与每个产量上当前在枚举对象中的版本计数器进行比较。 Finished. 完了 Obviously: change version on every change. 显然:每次更改都会更改版本。

Now, "i didn't find anything solid" - did it ever occur to you to - ah - read the source code? 现在,“我没有发现任何可靠的东西”-您曾经想过-啊-阅读源代码吗? It is all public, you know... 都是公开的,你知道的...

http://referencesource.microsoft.com/ http://referencesource.microsoft.com/

you look for mscorlib. 您正在寻找mscorlib。

FOr example, ArrayList: http://referencesource.microsoft.com/#mscorlib/system/collections/arraylist.cs 例如ArrayList: http ://referencesource.microsoft.com/#mscorlib/system/collections/arraylist.cs

It does not get more solid than that. 没有比这更可靠的了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM