让lambda引用自己

时间:2014-09-16 19:50:58

标签: c# lambda

我试图让lambda能够引用自己,例如:

PictureBox pictureBox=...;
Request(() => {
    if (Form1.StaticImage==null)
        Request(thislambda); //What to change to the 'thislambda' variable?
    else
        pictureBox.Image=Form1.StaticImage; //When there's image, then just set it and quit requesting it again
});

当我尝试将lambda放在变量中时,lambda引用自身,当然是错误。

我想过用一种能够调用自身的方法创建类,但我想坚持使用lambda。 (虽然它目前只给出了可读性而且没有任何优点)

3 个答案:

答案 0 :(得分:22)

您需要声明委托,将其初始化为某些,这样您就不会访问未初始化的变量,然后使用您的lambda初始化它。

Action action = null;
action = () => DoSomethingWithAction(action);

我看到的最常见用法可能是事件处理程序在触发时需要从事件中删除自身:

EventHandler handler = null;
handler = (s, args) =>
{
    DoStuff();
    something.SomeEvent -= handler;
};
something.SomeEvent += handler;

答案 1 :(得分:1)

从C#7开始,您还可以使用本地函数:

PictureBox pictureBox=...;
void DoRequest() {
    if (Form1.StaticImage == null)
        Request(DoRequest);
    else
        pictureBox.Image = Form1.StaticImage; //When there's image, then just set it and quit requesting it again
}

Request(DoRequest);

答案 2 :(得分:0)

以下是专家关于这个主题的有趣帖子 - http://blogs.msdn.com/b/wesdyer/archive/2007/02/02/anonymous-recursion-in-c.aspx

摘自帖子 - "一个快速的解决方法是将值null赋给fib,然后将lambda赋给fib。这会导致在使用之前明确分配fib。

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

但是我们的C#解决方法并没有真正使用递归。递归要求函数调用自身。&#34;

如果您正在寻找其他有趣的方法,请阅读整篇文章。