Ham*_*ith 13
在C#中,lambda运算符写成"=>"(通常在朗读时发音为" 转到 ").这意味着左侧的参数被传递到右侧的代码块(lambda函数/匿名委托).
因此,如果您有一个Func或Action(或任何具有更多类型参数的表兄弟),那么您可以为它们分配一个lambda表达式,而不是需要实例化一个委托或者为延迟处理设置一个单独的方法:
//creates a Func that can be called later
Func<int,bool> f = i => i <= 10;
//calls the function with 12 substituted as the parameter
bool ret = f(12);
Run Code Online (Sandbox Code Playgroud)
既然没人提到它,在VB.NET中你会使用function关键字而不是=>,如下所示:
dim func = function() true
'or
dim func1 = function(x, y) x + y
dim result = func() ' result is True
dim result1 = func1(5, 2) ' result is 7
Run Code Online (Sandbox Code Playgroud)
这是声明lambda的简写.
i => i++
Run Code Online (Sandbox Code Playgroud)
是(某种)与写作相同:
delegate(int i)
{
i++;
}
Run Code Online (Sandbox Code Playgroud)
在以下情况下:
void DoSomething(Action<int> doSomething)
{
doSomething(1);
}
DoSomething(delegate(int i) { i++; });
//declares an anonymous method
//and passes it to DoSomething
Run Code Online (Sandbox Code Playgroud)
这与写作相同(有点):
void increment(int i)
{
i++;
}
Run Code Online (Sandbox Code Playgroud)
只是没有给它起一个名字,它允许你在线声明一个函数,称为"匿名"函数.