Some help understanding “yield”

前端 未结 8 1174
挽巷
挽巷 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:41

    A method using yield return must be declared as returning one of the following two interfaces:

    IEnumerable
    IEnumerator
    

    (thanks Jon and Marc for pointing out IEnumerator)

    Example:

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

    yield is a lazy producer of data, only producing another item after the first has been retrieved, whereas returning a list will return everything in one go.

    So there is a difference, and you need to declare the method correctly.

    For more information, read Jon's answer here, which contains some very useful links.

提交回复
热议问题