Python中的yield和C#中的yield之间的差异

时间:2009-11-09 23:13:42

标签: c# python

Python中的yield关键字和C#中的yield关键字有什么区别?

4 个答案:

答案 0 :(得分:28)

C#的yield return相当于Python的yieldyield break只是Python中的return

除了那些微小的差异外,它们的目的基本相同。

答案 1 :(得分:14)

这可以帮助您理解它:Iterators in C#, Python, and Ruby

答案 2 :(得分:12)

最重要的区别是python yield会给你一个迭代器,一旦完全迭代就结束了。

但C#yield return为您提供了一个迭代器“ factory”,您可以将其传递并在代码的多个位置使用它,而不必考虑它是否曾经“循环”过一次。 / p>

在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]:

在C#中:

class Program
{
    static IEnumerable<int> 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);
    }
}

这会给你:

0
1
2
0
1
2

答案 3 :(得分:0)

除了其他答案外,要注意的一个重要区别是C#中的yield不能用作表达式,只能用作语句。

Python中yield表达式用法的示例(从here粘贴的示例):

def echo(value=None):
  print "Execution starts when 'next()' is called for the first time."
  try:
    while True:
       try:
         value = (yield value)
       except GeneratorExit:
         # never catch GeneratorExit
         raise
       except Exception, e:
         value = e
     finally:
       print "Don't forget to clean up when 'close()' is called."

generator = echo(1)
print generator.next()
# Execution starts when 'next()' is called for the first time.
# prints 1

print generator.next()
# prints None

print generator.send(2)
# prints 2

generator.throw(TypeError, "spam")
# throws TypeError('spam',)

generator.close()
# prints "Don't forget to clean up when 'close()' is called."