What is the yield keyword used for in C#?

后端 未结 17 2041
盖世英雄少女心
盖世英雄少女心 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 05:57

    At first sight, yield return is a .NET sugar to return an IEnumerable.

    Without yield, all the items of the collection are created at once:

    class SomeData
    {
        public SomeData() { }
    
        static public IEnumerable CreateSomeDatas()
        {
            return new List {
                new SomeData(), 
                new SomeData(), 
                new SomeData()
            };
        }
    }
    

    Same code using yield, it returns item by item:

    class SomeData
    {
        public SomeData() { }
    
        static public IEnumerable CreateSomeDatas()
        {
            yield return new SomeData();
            yield return new SomeData();
            yield return new SomeData();
        }
    }
    

    The advantage of using yield is that if the function consuming your data simply needs the first item of the collection, the rest of the items won't be created.

    The yield operator allows the creation of items as it is demanded. That's a good reason to use it.

提交回复
热议问题