简体   繁体   English

C#委托和lambdas…未指向预期的方法

[英]C# delegates and lambdas… not pointing to the expected method

I'm reading the blog about Y combinators and there's a mention of a snippet of code posted below: 我正在阅读有关Y组合器的博客,并且下面提到了一段代码:

http://blogs.msdn.com/b/wesdyer/archive/2007/02/02/anonymous-recursion-in-c.aspx 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

Huh!? ?!? Notice how the result of calling fib changes and that the result of calling fibCopy differs even from the result of calling fib! 请注意,调用fib的结果如何变化,并且调用fibCopy的结果甚至不同于调用fib的结果! (See if you can figure out why) (看看您是否能找出原因)

The poster mentions that this result will occur however, he doesn't mention why and I can't to see to figure it out either. 张贴者提到会出现这种结果,但是他没有提及原因,我也看不出来。 The way I see it is... 我的看法是...

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.... 

but obviously that's not what's going on. 但这显然不是事实。

Your explanation is correct. 您的解释是正确的。

fibCopy -> points to fib which is pointing to new lambda.... fibCopy->指向fib,它指向新的lambda。

The final fibCopy is still the original definition: 最终的fibCopy仍然是原始定义:

n => n > 1 ? fib(n - 1) + fib(n - 2) : n;

However, fib is no longer recursive, and invoking fibCopy(6) is actually running: 但是, fib不再是递归的,并且调用fibCopy(6)实际上正在运行:

n => n > 1 ? (n - 1) * 2 + (n - 2) * 2 : n

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM