Some help understanding “yield”

前端 未结 8 1142
挽巷
挽巷 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

    What does the method you're using this in look like? I don't think this can be used in just a loop by itself.

    For example...

    public IEnumerable<string> GetValues() {
        foreach(string value in someArray) {
            if (value.StartsWith("A")) { yield return value; }
        }
    }
    
    0 讨论(0)
  • 2020-11-30 02:41

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

    IEnumerable<SomethingAppropriate>
    IEnumerator<SomethingApropriate>
    

    (thanks Jon and Marc for pointing out IEnumerator)

    Example:

    public IEnumerable<AClass> 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.

    0 讨论(0)
提交回复
热议问题