你能帮我理解一下使用C#闭包的斐波那契的例子吗?

时间:2010-02-03 11:21:19

标签: c#

尝试学习C#功能,我将Dustin Campbell的fibonacci example移植到C#3。我的解决方案有效,但我无法理解Nth_Fib的最后一行。配方奶粉无关紧要,这不奇怪吗? n立即绑定在表达式“fn => Nth_Fib(n - 1)+ Nth_Fib(n - 2)”中,但我无法将构建的返回类型更改为Func< int>。这意味着我必须稍后传递一个冗余的参数?

注意:测试通过

[TestFixture]
public class TestFibClosure{
    [Test]
    public void test_fib(){
        Assert.AreEqual(8, new FibClosure().Nth_Fib(5));
        Assert.AreEqual(1597, new FibClosure().Nth_Fib(16));
    }
}

public class FibClosure{
    private Func<int, int>[] formulaCache;

    public int Nth_Fib(int n){
        if (n <= 2) return n;
        if(formulaCache == null) formulaCache = new Func<int, int>[(n + 1)];
        Func<int, int> formula = build(n);
        //doesn't matter, n is already bound !! ??
        return formula(334567);//same as formula(n)
    }

    private Func<int, int> build(int n){
        if (formulaCache[n] == null)
            formulaCache[n] = (fn => Nth_Fib(n - 1) + Nth_Fib(n - 2));
        return formulaCache[n];
    }
}

1 个答案:

答案 0 :(得分:4)

可以将类型更改为Func<int> - 你必须在任何地方都这样做:

public class FibClosure{
    private Func<int>[] formulaCache;

    public int Nth_Fib(int n){
        if (n <= 2) return n;
        if(formulaCache == null) formulaCache = new Func<int>[(n + 1)];
        Func<int> formula = build(n);
        return formula();
    }

    private Func<int> build(int n){
        if (formulaCache[n] == null)
            formulaCache[n] = () => Nth_Fib(n - 1) + Nth_Fib(n - 2);
        return formulaCache[n];
    }
}

你不需要函数的参数,因为它计算的Fibonacci值是固定的 - 基本上formulaCache[x]将计算fib(x)。这样做的线索就是你无论如何都没有在fn的lambda表达式中使用build

我不确定我会说这是一种非常明确的结构化方式,不可否认......