来自IEnumerator的IEnumerable [英] IEnumerable from IEnumerator
问题描述
我写了关于自定义IEnumerator
的文章.用它制作IEnumerable
的最简单方法是什么?理想的解决方案(一行代码)将是为此目的是否有一些类.还是我必须创建自己的?
I have writen about custom IEnumerator
. Whats the simplest way to make IEnumerable
from it ? Ideal solution (one line of code) would be if there was some class for that purpose. Or do I have to create my own ?
推荐答案
我真的会用另一种方法来解决这个问题.虽然您可以(根据Mike P的出色回答)包装一个枚举器以假装为可枚举的,但有些事情您实际上并不能真正做得到-例如,它被 hoped (尽管,公平地说,不是坚持),您可以从可枚举的,理想的隔离且可重复的枚举中获取 multiple 枚举器.所以,如果我这样做:
I would really approach this the other way around; while you can (as per Mike P's excellent answer) wrap an enumerator to pretend to be enumerable, there are some things that you can't really do - for example, it is hoped (although, to be fair, not insisted) that you can obtain multiple enumerators from an enumerable, ideally isolated and repeatable. So if I do:
Assert.AreEqual(sequence.Sum(), sequence.Sum());
但是如果您将枚举器欺骗"为可枚举,则第二个序列将为空.或者,如果您同时进行这些操作-则很奇怪.并且有 个方法可以并行处理它们-考虑:
but if you "spoof" the enumerator into an enumerable, the second sequence will be empty. Or if you do them in parallel - just bizarre. And there are methods that process them in parallel - consider:
Assert.IsTrue(sequence.SequenceEqual(sequence));
这可以使两个枚举器同时转发 ,因此,如果您仅拥有一个枚举器,那么您将大为吃惊.
this works both enumerators forward at the same time, so if you only have one enumerator, you are fairly scuppered.
枚举器上有 重置,但这在很大程度上是设计错误,不应该使用(规范中甚至正式要求迭代器块抛出异常,如果调用它) ).
There is a reset on enumerators, but this is largely a design mistake and shouldn't be used (it is even a formal requirement in the spec that iterator blocks throw an exception if you call it).
一个更好的(IMO)问题是如何从可枚举中获取枚举器",在这种情况下,答案是调用GetEnumerator(),并记住检查以处置给迭代器"-或更简单地说,是使用foreach
".
A better (IMO) question is "how do I get an enumerator from an enumerable", in which case the answer is "call GetEnumerator(), and remember to check to dispose to iterator" - or in simpler terms "use foreach
".
这篇关于来自IEnumerator的IEnumerable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!