Ability to reset IEnumerator generated using yield (C#)

后端 未结 5 2130
情歌与酒
情歌与酒 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:31

    No, it is not possible. When the C# compiler processes an iterator (a method that contains a yield statement), the compiler generates a class that implements IEnumerable and IEnumerator. The generated class' implementation of Reset just throws a NotSupportedException. There is no way to influence this in current versions of C#.

    Instead, your calling code will need to request a new enumerator, i.e. begin a new foreach loop. Or you will need to forgo the language support (the yield statement) and write your own class which implements IEnumerator.

提交回复
热议问题