这更像是一个为什么的问题。开始了。
C# 7.0 添加了一个名为“本地函数”的新功能。下面是一段代码。
public int Fibonacci(int x)
{
if (x < 0) throw new ArgumentException("Less negativity please!", nameof(x));
return Fib(x).current;
(int current, int previous) Fib(int i)
{
if (i == 0) return (1, 0);
var (p, pp) = Fib(i - 1);
return (p + pp, p);
}
}
我不明白的是,它对同一方法进行递归调用。我们可以使用普通的 foreach 轻松实现这一点。那为什么是局部函数。
MSDN说
methods implemented as iterators commonly need a non-iterator wrapper method for eagerly checking the arguments at the time of the call. (The iterator itself doesn’t start running until MoveNext is called).
需要一些帮助来理解它的概念。
最佳答案
its doing a recursive call to the same method. We can easily achieve this with a normal foreach
这是两种不同的东西:尾递归(方法在方法本身的末尾调用自身)或遍历集合。它们并不总是可以互换的,但它们可用于实现相同的最终结果。
局部函数只不过是一个类方法,其范围仅限于声明它的方法体。
局部函数的用途远不止递归。这是防止在多个 block 中重复代码的简单方法。
关于c# - C#7.0 中的局部函数与 foreach 或循环有何不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47326782/