When to use Yield?
什么时候应该使用退货率,何时只能使用退货?
yield
结构用于创建一个可以连续生成多个值的迭代器:
IEnumerable<int> three_numbers() {
yield return 1;
yield return 2;
yield return 3;
}
...
foreach (var i in three_numbers()) {
// i becomes 1, 2 and 3, in turn.
}
Use yield when you are returning an enumerable, and you don't have all the results at that point.
Practically, I've used yield when I want to iterate through a large block of information (database, flat file, etc.), and I don't want to load everything in memory first. Yield is a nice way to iterate through the block without loading everything at once.
Yield is for iterators.
It lets you process a list in small swallows, which is nice for big lists.
The magical thing about Yield is that it remembers where you're up to between invocations.
If you're not iterating you don't need Yield.
链接地址: http://www.djcxy.com/p/9112.html上一篇: 你将如何实现IEnumerator接口?
下一篇: 何时使用Yield?