重用 IEnumerable导致错误结果,例如在 .Any() 上
我在延迟执行领域有点迷失:
我声明了一个 IEnumerable 实现类的实例
var wordEnumerable = new WordEnumerable(_text);
,然后我迭代它(第一个单词是“Lorem”)
foreach (var word in wordEnumerable)
Console.WriteLine(word);
..它被写入控制台。
现在,在代码中,我执行了
Console.WriteLine(wordEnumerable.Any(w => w == "Lorem"));
.. 并得到 False 作为输出。
现在,如果我将 .Any(..) 部分放在 foreach 循环上方,我确实会得到 true,但是循环确实从第二个单词开始。
我的期望是 .Net 为每次调用 IEnumerable 及其底层 IEnumerator 创建不同的运行时“上下文”,这样它们就不会干扰...我不想通过以下方式 .Reset() 它手以获得正确的结果?
我在这里缺少什么?
更新:
- 链接到 IEnumerable 实现:https://gist.github.com/814352
- 链接到 IEnumerator 实现: https://gist.github.com/814354
- .. 最后是底层文本解析器实现: https://gist.github.com/814358
..它基本上是一个 IEnumerable这允许我迭代给定字符串中的单词。
I'm a little lost in deferred execution land:
I declare an instance of an IEnumerable implementing class
var wordEnumerable = new WordEnumerable(_text);
Then I iterate over it (the first word is "Lorem")
foreach (var word in wordEnumerable)
Console.WriteLine(word);
.. which is written to the console.
Now right thereafter in code I do a
Console.WriteLine(wordEnumerable.Any(w => w == "Lorem"));
.. and get a False as output.
Now If I put the .Any(..) part above the foreach loop I do get a true, however the loop does start with the second word.
My expectation was that .Net creates different runtime 'contexts' for each call to an IEnumerable and its underlying IEnumerator so they don't interfere... I wouldn't want to .Reset() it by hand in order to get a proper result?
What am I missing here?
Update:
- Link to IEnumerable implementation: https://gist.github.com/814352
- Link to IEnumerator implementation: https://gist.github.com/814354
- .. and finally the underlying text parser implementation: https://gist.github.com/814358
.. It is basically an IEnumerable that allows me to iterate over the words within a given string.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的期望是正确的 -
Any
将再次调用GetEnumerator
以获取新的IEnumerator
。如果您正确实现了IEnumerable
,应该没问题。我的猜测是您的WordEnumerable
实现不正确。请发布代码:)如果你写: 会发生什么
?另一件要检查的事情是
WordEnumerable
实现IEnumerable
而不是IEnumerable
Your expectation is correct -
Any
will callGetEnumerator
again to get a freshIEnumerator<T>
. That should be fine if you've implementedIEnumerable<T>
correctly. My guess is that your implementation ofWordEnumerable
is incorrect. Please post the code :)What happens if you write:
? The other thing to check is that
WordEnumerable
implementsIEnumerable<string>
rather thanIEnumerable<object>
, otherwise your==
check will be a reference identity check.