Ability to reset IEnumerator generated using yield (C#)

后端 未结 5 2026
情歌与酒
情歌与酒 2021-02-05 08:00

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

5条回答
  •  渐次进展
    2021-02-05 08:45

    There's a nice workaround that I just discovered. Make your generator method return IEnumerable, not IEnumerator. Then you can do

    var values = MyGeneratorMethod();
    var enumerator = values.GetEnumerator();
    // ... do stuff with enumerator
    enumerator = values.GetEnumerator(); // instead of enumerator.Reset();
    

    I believe itowlson's answer suggested this exact trick, but I couldn't understand it until I heard of the trick elsewhere.

提交回复
热议问题