C#无限迭代 [英] C# infinite iteration
问题描述
C#中是否有与Java的Stream.iterate
类似的东西?我能找到的最接近的东西是Enumerable.Range
,但有很大的不同.
Is there anything similar in C# to Java's Stream.iterate
? The closest thing I could find was Enumerable.Range
but it is much different.
我问的原因是我一直在观看演示讲述了良好的编程原理,并且有一个关于声明式和命令式代码的线程.引起我注意的是一种可以生成伪无限数据集的方法.
The reason I'm asking is that I've been just watching some presentation about good programming principles and there was a thread about declarative vs. imperative code. What caught my attention was a way you can generate a pseudo-infinite set of data.
推荐答案
.Net框架中没有完全相同的等效项,但MoreLINQ库:
There isn't an exact equivalent in the .Net framework but there is one in the MoreLINQ library:
foreach (var current in MoreEnumerable.Generate(5, n => n + 2).Take(10))
{
Console.WriteLine(current);
}
使用yield
重新创建它也很简单:
It's also very simple to recreate it using yield
:
public static IEnumerable<T> Iterate<T>(T seed, Func<T,T> unaryOperator)
{
while (true)
{
yield return seed;
seed = unaryOperator(seed);
}
}
yield
允许创建无限枚举器,因为:
yield
enables to create an infinite enumerator because:
在迭代器方法中到达yield return语句时,将返回expression,并保留代码中的当前位置.下次调用迭代器函数时,将从该位置重新开始执行.
When a yield return statement is reached in the iterator method, expression is returned, and the current location in code is retained. Execution is restarted from that location the next time that the iterator function is called.
这篇关于C#无限迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!