收益率 [英] yield return
问题描述
我正在使用yield return的可枚举函数。这允许我遍历每个循环使用的项目。由于这是一个惰性求值,每次迭代后控件都会返回到调用函数。
如何在没有每个循环的情况下使用可枚举函数?
public static IEnumerable< int> GetValuesUpto(int n)
{
for(int ctr = 1; ctr< = n; ctr ++)
{
yield return ctr;
}
}
所以,当我调用这个函数时,
int [] arr = GetValuesUpto(10);
结果是什么,它会像懒惰的评估一样工作,只返回第一个值,还是会返回所需的结果?
等待你的回复人!!
Vishwjeet
Hi,
I am using a enumerable function using "yield return". This allows me to iterate through the items using for each loop. Since this is a lazy evaluation, after each iteration the control returns to the calling function.
How can I use the enumerable function without for each loop?
public static IEnumerable<int> GetValuesUpto(int n)
{
for(int ctr = 1;ctr<=n;ctr++)
{
yield return ctr;
}
}
So, when I call this function i.e.
int[] arr = GetValuesUpto(10);
What would be the result, will it work like a lazy evaluation and will return only the first value, or will it return the desired result?
Waiting for your replies guys!!
Vishwjeet
推荐答案
当你调用迭代器块时想要从Enumerable中获取数据。
实际上如果你调用该函数,它将不会被调用。相反,如果你对Enumerable对象进行foreach,那么函数将被调用并将返回10. ;-)
只需像我一样改变你的代码:
Iterator blocks are called when you want to fetch the data from the Enumerable.
Actually if you call the the function, it will not be called. Rather if you do a foreach on the Enumerable object the function will be called and will return you 10. ;-)
Just change your code a bit as I did:
<br />IEnumerable<int> arr = Documented.GetValuesUpto(10);<br />MessageBox.Show(arr.ToList<int>().Count.ToString());
public static IEnumerable<int> GetValuesUpto(int n)<br />{<br /><br /> for (int ctr = 1; ctr <= n; ctr++)<br /> {<br /><br /> yield return ctr;<br /> }<br /> <br />}
在行中放置一个断点 IEnumerable< int> arr = Documented.GetValuesUpto(10);
。以及 GetValueUpto
块内的断点。当我们尝试调用 ToList
()而不是实际调用 GetValueUpto
时,您将看到调用该函数。这是迭代器块的主要优点。
[玫瑰] [玫瑰]
Put a breakpoint in the line IEnumerable<int> arr = Documented.GetValuesUpto(10);
. and also a breakpoint within GetValueUpto
block. You will see the function is called when we try to call ToList
() rather than the actual call to GetValueUpto
. This is the main advantage of iterator blocks.
[Rose][Rose]
这篇关于收益率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!