"=>"是什么意思?

Den*_*ail 13 .net c# lambda .net-3.5

原谅我,如果这会尖叫新手,但=>在C#中意味着什么?我上周在一个演示文稿中,这个操作符(我认为)是在ORM的上下文中使用的.在我回到笔记之前,我并没有真正关注语法的细节.

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)

  • 我从来没有注意到当你用'小于或等于'来保持lambda时会有多么混乱.它最终看起来像所有箭头指向我. (4认同)

Ric*_*ein 8

既然没人提到它,在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)


Rex*_*x M 7

这是声明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)

只是没有给它起一个名字,它允许你在线声明一个函数,称为"匿名"函数.