加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何在不迭代的情况下放弃IEnumerator?

发布时间:2020-12-15 08:09:07 所属栏目:百科 来源:网络整理
导读:考虑以下代码,第一个演示当我们完成对IEnumerable字符串的迭代时执行“清理”.第二遍是让我悲伤的原因.我需要能够在到达结束之前放弃IEnumerable,然后执行清理代码.但如果你运行这个,你会发现在第二次通过时,清理工作永远不会开火. 放弃像这样的IEnumerable
考虑以下代码,第一个演示当我们完成对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");
}

解决方法

您需要将迭代器方法的主要部分放入try..finally,并使用finally中的清理代码:
public IEnumerable<string> readColors()
    {
        try
        {
            string[] colors = { "red","blue" };
            for (int i = 0; i < colors.Length; i++)
                yield return colors[i];
        }
        finally
        {
            Console.WriteLine("Cleanup goes here");
        }
    }

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读