问题描述
我见过的在 C# 方法中使用 yield return x; 的所有示例都可以通过返回整个列表以相同的方式完成.在这些情况下,使用 yield return 语法与返回列表相比有什么好处或优势吗?
All of the examples I've seen of using yield return x; inside a C# method could be done in the same way by just returning the whole list. In those cases, is there any benefit or advantage in using the yield return syntax vs. returning the list?
另外,yield return 会在哪些类型的场景中使用,而您不能只返回完整列表?
Also, in what types of scenarios would yield return be used that you couldn't just return the complete list?
推荐答案
但是如果你自己建立一个集合呢?
But what if you were building a collection yourself?
一般来说,迭代器可用于懒惰地生成对象序列.例如 Enumerable.Range 方法内部没有任何类型的集合.它只是按需生成下一个数字.使用状态机生成这种惰性序列有很多用途.其中大部分都包含在函数式编程概念中.
In general, iterators can be used to lazily generate a sequence of objects. For example Enumerable.Range method does not have any kind of collection internally. It just generates the next number on demand. There are many uses to this lazy sequence generation using a state machine. Most of them are covered under functional programming concepts.
在我看来,如果您将迭代器视为枚举集合的一种方式(它只是最简单的用例之一),那么您就走错了路.正如我所说,迭代器是返回序列的方法.该序列甚至可能是无限.没有办法返回一个无限长的列表并使用前 100 个项目.它不得不有时很懒惰.返回一个集合与返回一个集合生成器有很大的不同(这是一个迭代器).它正在将苹果与橙子进行比较.
In my opinion, if you are looking at iterators just as a way to enumerate through a collection (it's just one of the simplest use cases), you're going the wrong way. As I said, iterators are means for returning sequences. The sequence might even be infinite. There would be no way to return a list with infinite length and use the first 100 items. It has to be lazy sometimes. Returning a collection is considerably different from returning a collection generator (which is what an iterator is). It's comparing apples to oranges.
假设示例:
static IEnumerable<int> GetPrimeNumbers() {
for (int num = 2; ; ++num)
if (IsPrime(num))
yield return num;
}
static void Main() {
foreach (var i in GetPrimeNumbers())
if (i < 10000)
Console.WriteLine(i);
else
break;
}
此示例打印小于 10000 的素数.您可以轻松地将其更改为打印小于一百万的数字,而无需触及素数生成算法.在此示例中,您无法返回所有素数的列表,因为该序列是无限的,并且消费者甚至不知道从一开始就需要多少项目.
This example prints prime numbers less than 10000. You can easily change it to print numbers less than a million without touching the prime number generation algorithm at all. In this example, you can't return a list of all prime numbers because the sequence is infinite and the consumer doesn't even know how many items it wants from the start.
这篇关于在 C# 中使用 yield return 迭代器的目的/优势是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)