Usefulness of yield

This question already has an answer here:

  • What is the yield keyword used for in C#? 16 answers

  • yield return is a lot more flexible when the data structure is not linear.

    For example, you could use it to enumerate a tree in preorder, postorder, or inorder:

    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;
    }
    

    You could also produce a method that yields a sequence of Fibonacci numbers:

    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/9096.html

    上一篇: 正确使用“收益回报”

    下一篇: 收益的有用性