C#delegates和lambdas ......没有指向预期的方法

时间:2016-01-22 03:31:26

标签: c#

我正在阅读有关Y组合器的博客,并且提到了下面发布的一段代码:

http://blogs.msdn.com/b/wesdyer/archive/2007/02/02/anonymous-recursion-in-c.aspx

Func<int, int> fib = null;
fib = n => n > 1 ? fib(n - 1) + fib(n - 2) : n;
Func<int, int> fibCopy = fib;
Console.WriteLine(fib(6));                        // displays 8
Console.WriteLine(fibCopy(6));                    // displays 8
fib = n => n * 2;
Console.WriteLine(fib(6));                        // displays 12
Console.WriteLine(fibCopy(6));                    // displays 18
  

咦!?注意调用fib的结果如何改变   调用fibCopy的结果甚至与调用fib的结果不同!   (看看你能弄清楚原因)

海报提到这个结果会发生,然而,他没有提到为什么,我也看不出也想出来。我看待它的方式是......

fib -> Points to fib sequence lambda
fibCopy -> Points to fib sequence lambda
lambda -> n * 2
fib -> points to new lambda
fibCopy -> points to fib which is pointing to new lambda.... 

但很明显,这不是正在发生的事情。

1 个答案:

答案 0 :(得分:3)

你的解释是正确的。

  

fibCopy - &gt;指向指向新lambda的fib ......

最终的import matplotlib.pyplot as pl def anomaly_selection(indexes, fig, ax): selected = [] for i in range(0, len(indexes)): index = indexes[i] ax.set_xlim(index-100, index+100) ax.autoscale_view() fig.canvas.draw() print("[%d/%d] Index %d " % (i, len(indexes), index), end="") while True: response = input("Particle? ") if response == "y": selected.append(index) break elif response == "x": return selected elif response == "n": break fig, ax = pl.subplots(2, sharex=True) ax[0].plot([1, 2, 3, 4, 5]) # just pretend data pl.show(block=False) sel = anomaly_selection([100, 1000, 53000, 4300], fig, ax[0]) 仍然是最初的定义:

fibCopy

但是,n => n > 1 ? fib(n - 1) + fib(n - 2) : n; 不再是递归的,并且调用fib实际上正在运行:

fibCopy(6)