Ability to reset IEnumerator generated using yield (C#)

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

    This code implements an attribute that can be set to reset the enumerator. Notes:

    • Unfortunately, this method of resetting won't work with multiple enumerators instances
    • This doesn't reset it via the interface, but actually via setting a property either directly or through a method
    • Given the complexity and the fragility, I actually wouldn't recommend this approach
    • I'm actually wondering if a goto might be neater

    Code:

    public IEnumerator GetEnumerator(){
        do{
            this.shouldReset=FALSE;
            for (Entry e = this.ReadEntry(); e != null; e = this.ReadEntry()){
                if(self.shouldReset)break;
                else yield return e;
            }
        }
        while(self.shouldReset)
    }
    

提交回复
热议问题