10

I haven't really come across this syntax during my Programming classes in Uni before and I'm curious as to what it means.

The only times I've had to implement it was:

  1. When I had to create a BackgroundWorker that had to be added to the ProgressChanged event

    Invoke((MethodInvoker)(() => updatePing((int) e.UserState)));

  2. When researching tutorials on using the Caliburn.Micro MVVM framework

    NotifyOfPropertyChange(() => Count);

I have tried searching around on what this notation means but the special characters it uses seem to mess with google search and I have no idea what it is called.

4

2 回答 2

22

lambda 表达式=>is 语法。

表示没有参数 - 如果有参数并且可以从上下文中推断出类型,()则可以将它们指定为如下所示:

(x, y) => x + y

或明确指定类型

(int x, string y) => x + y.Length

如果只有一个参数并且可以推断其类型,则不需要括号:

x => x.Length
于 2013-05-15T17:47:43.230 回答
10

这是一个没有参数的 lambda 表达式。

您真正在做的是将 a delegate(有点像方法的变量)传递给您的函数


() => Count表示类似于以下的方法

type methodName()
{
    return Count;
}
于 2013-05-15T17:48:14.077 回答