我该如何使用IEnumerator.Reset()?
是如何完全正确的方法来调用IEnumerator.Reset$c$c>?
How exactly is the right way to call IEnumerator.Reset
?
该文件说:
在重置
方法提供了COM互操作性。它不一定需要被执行;相反,实施者可以简单地抛出一个 NotSupportedException异常
。
The
Reset
method is provided for COM interoperability. It does not necessarily need to be implemented; instead, the implementer can simply throw aNotSupportedException
.
好了,这是否意味着我不应该永远把它?
Okay, so does that mean I'm not supposed to ever call it?
这是的这样的诱人用于流量控制例外:
It's so tempting to use exceptions for flow control:
using (enumerator = GetSomeExpensiveEnumerator())
{
while (enumerator.MoveNext()) { ... }
try { enumerator.Reset(); } //Try an inexpensive method
catch (NotSupportedException)
{ enumerator = GetSomeExpensiveEnumerator(); } //Fine, get another one
while (enumerator.MoveNext()) { ... }
}
是,我们应该如何使用它呢?或者,我们不是为了从托管code使用它呢?
Is that how we're supposed to use it? Or are we not meant to use it from managed code at all?
从来没有的;最终这是一个错误。正确的方法来遍历序列比一次更多的是 .GetEnumerator()
再次呼吁 - 即使用的foreach
了。如果你的数据是不可重复的(或昂贵的重复),通过 .ToList()
或类似的缓冲吧。
never; ultimately this was a mistake. The correct way to iterate a sequence more than once is to call .GetEnumerator()
again - i.e. use foreach
again. If your data is non-repeatable (or expensive to repeat), buffer it via .ToList()
or similar.
这是语言规范的迭代器块抛出异常此方法正式的需求的。因此,您的不能依赖于它的工作的。曾经。
It is a formal requirement in the language spec that iterator blocks throw exceptions for this method. As such, you cannot rely on it working. Ever.