What is the yield keyword used for in C#?

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

    The yield keyword actually does quite a lot here.

    The function returns an object that implements the IEnumerable interface. If a calling function starts foreaching over this object, the function is called again until it "yields". This is syntactic sugar introduced in C# 2.0. In earlier versions you had to create your own IEnumerable and IEnumerator objects to do stuff like this.

    The easiest way understand code like this is to type-in an example, set some breakpoints and see what happens. Try stepping through this example:

    public void Consumer()
    {
        foreach(int i in Integers())
        {
            Console.WriteLine(i.ToString());
        }
    }
    
    public IEnumerable Integers()
    {
        yield return 1;
        yield return 2;
        yield return 4;
        yield return 8;
        yield return 16;
        yield return 16777216;
    }
    

    When you step through the example, you'll find the first call to Integers() returns 1. The second call returns 2 and the line yield return 1 is not executed again.

    Here is a real-life example:

    public IEnumerable Read(string sql, Func make, params object[] parms)
    {
        using (var connection = CreateConnection())
        {
            using (var command = CreateCommand(CommandType.Text, sql, connection, parms))
            {
                command.CommandTimeout = dataBaseSettings.ReadCommandTimeout;
                using (var reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        yield return make(reader);
                    }
                }
            }
        }
    }
    

    提交回复
    热议问题