如何在不迭代到最后的情况下放弃IEnumerator?

Ral*_*ton 7 c#

考虑以下代码,第一个演示当我们完成对IEnumerable字符串的迭代时执行"清理".第二遍是让我悲伤的原因.我需要能够在到达结束之前放弃IEnumerable,然后执行清理代码.但是如果你运行这个,你会发现在第二次通过时,清理工作永远不会发生.

放弃像这样的IEnumerable的首选方法是什么?

static void Main(string[] args)
{
    // first pass
    foreach (String color in readColors())
        Console.WriteLine(color);

    // second pass
    IEnumerator<string> reader = readColors().GetEnumerator();
    if (reader.MoveNext())
    {
        Console.WriteLine(reader.Current);
        reader.Dispose();
    }
}
static IEnumerable<string> readColors()
{
    string[] colors = { "red", "green", "blue" };
    for (int i = 0; i < colors.Length; i++)
        yield return colors[i];

    Console.WriteLine("Cleanup goes here");
}
Run Code Online (Sandbox Code Playgroud)

Rob*_*ine 7

您需要将迭代器方法的主要部分放入try..finally,并使用finally中的清理代码:

   public IEnumerable<string> readColors()
    {
        try
        {
            string[] colors = { "red", "green", "blue" };
            for (int i = 0; i < colors.Length; i++)
                yield return colors[i];
        }
        finally
        {
            Console.WriteLine("Cleanup goes here");
        }
    }
Run Code Online (Sandbox Code Playgroud)

请记住,在引擎盖下,迭代器方法会导致创建一个单独的类,实现IEnumerableIEnumerator.通过将清理放在finally块中,它最终会生成在生成的类' Dispose方法中.

[ 编辑:(正如其他答案中所指出的)更喜欢using关于Dispose手动调用方法的陈述.我假设你这样做只是为了突出讨论中的问题,但无论如何都值得指出]