What is the yield keyword used for in C#?

后端 未结 17 2028
盖世英雄少女心
盖世英雄少女心 2020-11-22 05:26

In the How Can I Expose Only a Fragment of IList<> question one of the answers had the following code snippet:

IEnumerable FilteredList()
{
         


        
      
      
      
17条回答
  •  故里飘歌
    2020-11-22 06:03

    It's trying to bring in some Ruby Goodness :)
    Concept: This is some sample Ruby Code that prints out each element of the array

     rubyArray = [1,2,3,4,5,6,7,8,9,10]
        rubyArray.each{|x| 
            puts x   # do whatever with x
        }
    

    The Array's each method implementation yields control over to the caller (the 'puts x') with each element of the array neatly presented as x. The caller can then do whatever it needs to do with x.

    However .Net doesn't go all the way here.. C# seems to have coupled yield with IEnumerable, in a way forcing you to write a foreach loop in the caller as seen in Mendelt's response. Little less elegant.

    //calling code
    foreach(int i in obCustomClass.Each())
    {
        Console.WriteLine(i.ToString());
    }
    
    // CustomClass implementation
    private int[] data = {1,2,3,4,5,6,7,8,9,10};
    public IEnumerable Each()
    {
       for(int iLooper=0; iLooper

提交回复
热议问题