能够重新使用的IEnumerator产生的收益(C#) [英] Ability to reset IEnumerator generated using yield (C#)

查看:185
本文介绍了能够重新使用的IEnumerator产生的收益(C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我用产量来代替手工创建一个IEnumerator的,是有可能实现IEnumerator.Reset?

If I use yield instead of manually creating an IEnumerator, is it possible to implement IEnumerator.Reset?

推荐答案

有没有内置的支持,但是你可以定义自己的实现的IEnumerator 的代表们所有的方法都被C#所产生的枚举,并只允许你定义的<你自己的行为。code>重置法

There is no built-in support, but you can define your own implementation of IEnumerator that delegates all method calls to the enumerator generated by C# and only lets you define your own behavior for the Reset method.

之类的最简单的版本是这样的:

The simplest version of the class would look like this:

class ResetableEnumerator<T> : IEnumerator<T>
{
  public IEnumerator<T> Enumerator { get; set; }
  public Func<IEnumerator<T>> ResetFunc { get; set; }

  public T Current { get { return Enumerator.Current; } }
  public void  Dispose() { Enumerator.Dispose(); }
  object IEnumerator.Current { get { return Current; } }
  public bool  MoveNext() { return Enumerator.MoveNext(); }
  public void  Reset() { Enumerator = ResetFunc(); }
}

在这种情况下, ResetFunc 您指定返回一个新的的IEnumerator< T> ,所以你提供的实施 ResetFunc 可以做一些。清理或任何你重置,然后返回一个新的枚举时需要做的。

In this case, the ResetFunc that you specify returns a new IEnumerator<T>, so your provided implementation of ResetFunc can do some cleanup or whatever you need to do when resetting and then return a new enumerator.

IEnumerator<int> Foo() { /* using yield return */ }
IEnumerator<int> PublicFoo() {
  return new ResetableEnumerator<int> { 
    Enumerator = Foo(),
    ResetFunc = () => { 
      Cleanup();
      return Foo(); } };
}

您将需要存储的<$ C的所有最初的局部变量$ C>富方法作为类的字段,这样就可以在访问它们清除(请注意,<$ C $其余C>富身体永远不会调用后重置)被执行,但是这仍然比写一个手写的迭代器容易!

You'll need to store all the originally local variables of the Foo method as fields of the class, so that you can access them in Cleanup (Note that the rest of the Foo body will never be executed after calling Reset), but that's still easier than writing a handwritten iterator!

这篇关于能够重新使用的IEnumerator产生的收益(C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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