Some help understanding “yield”

前端 未结 8 1171
挽巷
挽巷 2020-11-30 01:41

In my everlasting quest to suck less I\'m trying to understand the \"yield\" statement, but I keep encountering the same error.

The body of [someMetho

8条回答
  •  旧巷少年郎
    2020-11-30 02:28

    "yield" creates an iterator block - a compiler generated class that can implement either IEnumerable[] or IEnumerator[]. Jon Skeet has a very good (and free) discussion of this in chapter 6 of C# in Depth.

    But basically - to use "yield" your method must return an IEnumerable[] or IEnumerator[]. In this case:

    public IEnumerable SomeMethod() {
        // ...
        foreach (XElement header in headersXml.Root.Elements()){
            yield return (ParseHeader(header));                
        }
    }
    

提交回复
热议问题