What is the exact usage of Yield Keyword

This question already has an answer here:

  • What is the yield keyword used for in C#? 16 answers

  • Straight from MSDN

    You use a yield return statement to return each element one at a time.When a yield return statement is reached in the iterator method, expression is returned, and the current location in code is retained. Execution is restarted from that location the next time that the iterator function is called.

    EDIT: To get the details see this series of articles.


    It is a waste to use yield return to wrap something that is already an IEnumerable.

    yield return can be used to wrap something not IEnumerable into an IEnumerable.

    Such as this:

    public IEnumerable<string> GetNames()
    {
        yield return "Cow";
        yield return "Goat";
        yield return "Lion";
        yield return "Deer";
    }
    

    Or something that actually makes sense, such as a tree traversal.


    例:

     public IEnumerable<MyClass> GetList()
     {
         foreach (var item in SomeList)
         {
              yield return new MyClass();
         }
     }
    
    链接地址: http://www.djcxy.com/p/9092.html

    上一篇: 在编写一个枚举时,什么产生return var?

    下一篇: Yield关键字的确切用法是什么?