問題描述
我見過的在 C# 方法中使用 yield return x;
的所有示例都可以通過返回整個列表以相同的方式完成.在這些情況下,使用 yield return
語法與返回列表相比有什么好處或優(yōu)勢嗎?
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
方法內(nèi)部沒有任何類型的集合.它只是按需生成下一個數(shù)字.使用狀態(tài)機生成這種惰性序列有很多用途.其中大部分都包含在函數(shù)式編程概念中.
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 的素數(shù).您可以輕松地將其更改為打印小于一百萬的數(shù)字,而無需觸及素數(shù)生成算法.在此示例中,您無法返回所有素數(shù)的列表,因為該序列是無限的,并且消費者甚至不知道從一開始就需要多少項目.
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 迭代器的目的/優(yōu)勢是什么?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!