增加产量关键字的值? [英] Yield keyword value added?

查看:102
本文介绍了增加产量关键字的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仍然试图寻找在那里我会在真实情况下使用的收益的关键字。

still trying to find where i would use the "yield" keyword in a real situation.

我看到关于这一主题

的http://计算器。 COM /问题/ 39476 /什么,是最产量关键字用来换在-C

但在接受的答案,他们有这是哪里有人遍历各地整数()

but in the accepted answer, they have this as an example where someone is iterating around Integers()

public IEnumerable<int> Integers()
{
yield return 1;
yield return 2;
yield return 4;
yield return 8;
yield return 16;
yield return 16777216;
}



但为什么不使用

but why not just use

list<int>



而不是在这里。似乎更直接。

here instead. seems more straightforward..

推荐答案

如果你建立并返回一个列表(说,它有1个万台),这是一大块内存,并且还创建工作吧。

If you build and return a List (say it has 1 million elements), that's a big chunk of memory, and also of work to create it.

有时呼叫者可能只想知道的第一个元素是什么。或者,他们可能希望将它们写入文件,因为他们得到他们,而不是建立在内存中的整个列表,然后将其写入文件。

Sometimes the caller may only want to know what the first element is. Or they might want to write them to a file as they get them, rather than building the whole list in memory and then writing it to a file.

这就是为什么它使更有意义的使用收益回报。它看起来并不建立整个列表并将其返回不同的,但因为整个名单并没有在内存中创建调用者可以看看第一个项目上之前它是非常不同的。

That's why it makes more sense to use yield return. It doesn't look that different to building the whole list and returning it, but it's very different because the whole list doesn't have to be created in memory before the caller can look at the first item on it.

当来电说:

foreach (int i in Integers())
{
   // do something with i
}

每个时间循环需要一个新的我,它可以运行更多的代码的整数()。该函数的代码为暂停,当它击中收益回报率语句。

Each time the loop requires a new i, it runs a bit more of the code in Integers(). The code in that function is "paused" when it hits a yield return statement.

这篇关于增加产量关键字的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆