我该如何使用IEnumerator.Reset()? [英] How Can I Use IEnumerator.Reset()?

查看:658
本文介绍了我该如何使用IEnumerator.Reset()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是如何完全正确的方法来调用<一个href="http://msdn.microsoft.com/en-us/library/system.collections.ienumerator.reset.aspx"><$c$c>IEnumerator.Reset?

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 a NotSupportedException.

好了,这是否意味着我不应该永远把它?

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.

这篇关于我该如何使用IEnumerator.Reset()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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