简体   繁体   English

python中的yield == C#中的yield return?

[英]yield in python == yield return in C#?

I haven't been able to find any info on using JUST yield in C# (when used for a generator). 我无法找到有关在C#中使用JUST yield的任何信息(用于生成器时)。 Is this because C# always uses yield with return? 这是因为C#始终将yield return一起使用吗? (yield return Object) (收益回报对象)

I think I'm confusing myself since I was learning the same topic (generators) in python today aswell, and so far i've only seen yield used alone in Python.. 自从我今天也在python中学习同一个主题(生成器)以来,我觉得自己很困惑,到目前为止,我只看到在Python中单独使用yield。

yield keyword is introduced by C# 2.0 in order to implement iteartion easier. C#2.0引入了yield关键字,以更轻松地实现迭代。 On the other hand it has some disadventages. 另一方面,它有一些缺点。 Let's first look at the yield keyword. 让我们首先看一下yield关键字。

public IEnumerable GetPowersofTwo()
{
   for (int i = 1; i < 10; i++)
       yield return (int)System.Math.Pow(2, i);
   yield break;
}

It is just a C# language feature. 它只是C#语言的功能。 During compilation Compiler converts yield method and its class to instances of IEnumerable and IEnumerator implemented classes. 在编译期间,编译器将yield方法及其类转换为IEnumerableIEnumerator实现的类的实例。

Criticism of the keyword yield 对关键字yield批评

yield has a couple of drawbacks first of all it is designed to simplify implementing iterations. 首先, yield具有两个缺点,旨在简化实现迭代。 But it can be used to write very ill designed code (like goto). 但是它可以用来编写非常糟糕的设计代码(例如goto)。 But using it for other than the intended purpose will make your code hard to follow. 但是,将其用于除预期目的以外的其他地方会使您的代码难以遵循。 Second problem is that "yield" does not make sense in Object Oriented paradigm just like delegates. 第二个问题是,在“面向对象”范式中,“收益”没有像委托那样有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM