收益的有用性

这个问题在这里已经有了答案:

  • 在C#中使用的yield关键字是什么? 16个答案

  • 当数据结构不是线性时, yield return更加灵活。

    例如,你可以用它来按顺序,后序或中序枚举一棵树:

    IEnumerable<T> InorderTree<T>(TreeNode<T> node) {
        if (node.Left != null) {
            foreach (var x in InorderTree(node.Left)) {
                yield return x;
            }
        }
        if (node.Right != null) {
            foreach (var x in InorderTree(node.Right)) {
                yield return x;
            }
        }
        yield return node.Value;
    }
    

    你也可以生成一个产生斐波那契数列序列的方法:

    IEnumerable<int> Fibonacci(int n) {
        int first = 0, second = 1;
        for (int c = 0 ; c < n ; c++ ) {
            int next;
            if ( c <= 1 ) {
                next = c;
            } else {
                next = first + second;
                first = second;
                second = next;
            }
            yield return next;
        }
    }
    
    链接地址: http://www.djcxy.com/p/9095.html

    上一篇: Usefulness of yield

    下一篇: When writing an enumerable, what does yield return var?