c# - C#7.0 中的局部函数与 foreach 或循环有何不同?

标签 c# .net foreach anonymous-function c#-7.0

这更像是一个为什么的问题。开始了。

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/

相关文章:

c# - 在 C# 中规范化目录名称

javascript - 如何在 C# 或 WPF 中执行 javascript 函数

c# - 从 ListView 检索到的错误数据

c# - 消除循环并改用 Linq

c# - EF Code First Migrations 创建额外的外键

c# - 我可以查询 Azure Web 作业队列吗?

java - IKVM.NET 和 Excel VBA

PHP PDO 查询,具有从数组中获取的多个条件

c# - 如何将datagridview数据导出到excel?

C# - 将大文件加载到 WPF RichTextBox 中?