使用IEnumerable检测修改 [英] Detecting modifications with an IEnumerable

查看:91
本文介绍了使用IEnumerable检测修改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个疑问,就是我还没有完全以这种格式被问到.

I have a question that I am surprised hasn't already been asked in exactly this format.

如果我有一个IEnumerable,它是基于对数据源的迭代生成的(并使用yield return语句),那么在通过Enumerator进行访问之后,如何检测到对源进行了修改?是通过GetEnumerator调用生成的?

If I have an IEnumerable that is generated based on iterating through a source of data, (and using a yield return statement), how can I detect when there has been a modification to the source after an access via an Enumerator that was generated via a GetEnumerator call?

这是一个奇怪的部分:我不是多线程的.我认为我的问题在某处存在缺陷,因为这应该很简单. . .我只想知道源代码何时更改且迭代器已过时.

Here is the strange part: I'm not multi-threading. I think my question has a flaw in it somewhere, because this should be simple. . . I just want to know when the source has changed and the iterator is out of date.

非常感谢您.

推荐答案

您需要自己创建枚举器才能跟踪此信息,或者至少将yield return;与您自己的修改跟踪类型配合使用地方.

You would need to handle creating the enumerator yourself in order to track this information, or, at a minimum use yield return; with your own type of modification tracking in place.

例如,大多数框架集合类都保留一个版本"号.当他们创建枚举器时,会保留该版本号的快照,并在MoveNext()期间对其进行检查.您可以在调用yield return XXX;

Most of the framework collection classes, for example, keep a "version" number. When they make an enumerator, they keep a snapshot of that version number, and check it during MoveNext(). You could make the same check before calling yield return XXX;

这篇关于使用IEnumerable检测修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆