Usefulness of yield
本问题已经有最佳答案,请猛点这里访问。
(P)I was wondering when EDOCX1 would be useful.It seems to me that I can use EDOCX1 commercial…Everytime I can use EDOCX1 commercial.(p)(P)让我说我有这个测试类(p)字母名称(P)第二个字母(p)字母名称(P)例1(p)(P)If I want to get a EDOCX1 theocx1(p)字母名称(P)但我可以做(p)字母名称(P)例2(p)(P)另一个字母(p)字母名称(P)But again,I could do(p)字母名称(P)有什么情况我不知道在哪里EDOCX1是最好的使用超过EDOCX1的语言吗?(p)
当数据结构不是线性时,
例如,您可以使用它来枚举一个树的预排序、后排序或顺序:
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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; } |
您还可以生成一个生成斐波那契数列的方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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; } } |