Difference between yield in Python and yield in C#

前端 未结 4 767
迷失自我
迷失自我 2021-02-05 03:14

What is the difference between yield keyword in Python and yield keyword in C#?

4条回答
  •  天涯浪人
    2021-02-05 03:29

    The most important difference is that python yield gives you an iterator, once it is fully iterated that's over.

    But C# yield return gives you an iterator "factory", which you can pass it around and uses it in multiple places of your code without concerning whether it has been "looped" once before.

    Take this example in python:

    In [235]: def func1():
       .....:     for i in xrange(3):
       .....:         yield i
       .....:
    
    In [236]: x1 = func1()
    
    In [237]: for k in x1:
       .....:     print k
       .....:
    0
    1
    2
    
    In [238]: for k in x1:
       .....:     print k
       .....:
    
    In [239]:
    

    And in C#:

    class Program
    {
        static IEnumerable Func1()
        {
            for (int i = 0; i < 3; i++)
                yield return i;
        }
    
        static void Main(string[] args)
        {
            var x1 = Func1();
            foreach (int k in x1) 
                Console.WriteLine(k);
    
            foreach (int k in x1)
                Console.WriteLine(k);
        }
    }
    

    That gives you:

    0
    1
    2
    0
    1
    2
    

提交回复
热议问题