Python和C#中yield的区别
Python中的yield
关键字和C#中的yield
关键字有什么不同呢?
3 个回答
1
需要注意一个重要的区别,除了其他回答之外,C#中的yield
不能用作表达式,只能作为语句使用。
下面是一个在Python中使用yield
表达式的例子(这个例子来自于这里):
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."
15
最重要的区别在于,Python中的yield会给你一个迭代器,一旦这个迭代器被完全遍历过,就不能再用了。
而C#中的yield return则给你一个迭代器的“工厂”,你可以把它传来传去,在代码的多个地方使用,而不需要担心它之前是否已经被“循环”过。
来看这个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
34
C#中的yield return
和Python中的yield
是一样的,yield break
在Python中就相当于return
。
除了这几个小差别,它们的主要功能基本上是一样的。