简体   繁体   English

IEnumerable产量和递归-不起作用

[英]IEnumerable yield and recursion - doesn't work

I'm trying to do something that combines using yield and recursion and I don't really understand why it's not working. 我正在尝试做结合使用收益和递归的事情,我真的不明白为什么它不起作用。

Since my code is complicated, I've generated a simple example with the Fibonacci series: 由于我的代码很复杂,因此我用斐波那契数列生成了一个简单的示例:

        private IEnumerable<int> fib()
        {
            int a1 = 1, a2 = 1;
            return fibRec(a1, a2);
        }

        private IEnumerable<int> fibRec(int a, int b)
        {
            int tmp = a;
            a = b;
            b = tmp + b;
            yield return a;
            fibRec(a, b);
        }

Now, I know there are a 1000 ways of solving Fibonacci, but it's not the deal here. 现在,我知道有1000种解决斐波那契的方法,但这不是解决方案。 this is only an example . 这只是一个例子

Here is my call: 这是我的电话:

var nums = fib().Take(50).ToList();

The recursive call doesn't "work". 递归调用不起作用。
I get the first yield to work OK and I don't really under stand why this suddenly stops when I try to call myself again. 我得到了第一笔可以正常工作的收益,而且我并没有真正理解为什么当我再次打电话给自己时突然停止这种收益。
Doing this with "while(true)" and no recursive call will work just fine. 使用“ while(true)”执行此操作,并且没有递归调用会很好地工作。

You need to iterate though the enumerable returned by the recursive call and yield return each of the items explicitly. 您需要迭代递归调用返回的可枚举,并让yield return显式yield return每个项目。

    private IEnumerable<int> fibRec(int a, int b)
    {
        int tmp = a;
        a = b;
        b = tmp + b;
        yield return a;
        foreach(int val in fibRec(a, b))
        {
             yield return val;
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM