简体   繁体   English

“(项目)=>”有什么作用?

[英]What does “(item) =>” do?

I'm trying to learn C# and MVC3.我正在尝试学习 C# 和 MVC3。 I wanted to have a WebGrid column as an Html.Action link, however, it wouldn't work until I did this:我想有一个 WebGrid 列作为 Html.Action 链接,但是,在我这样做之前它不会起作用:

grid.Column(format: (item) => Html.ActionLink("Edit", "Edit", new { id = item.Id }))

So I know that this fixes it but why?所以我知道这可以解决它,但为什么呢? The (item) looks like a cast but what is the => for? (item) 看起来像一个演员,但 => 是什么? From reading other questions I see that it's evidently bad to do this for some reason - why?通过阅读其他问题,我发现出于某种原因这样做显然很糟糕 - 为什么?

This is known as a lambda expression / anonymous function in C#.这在 C# 中称为 lambda 表达式/匿名 function。 The () portion is the argument list and the => indicates the right hand side is the body / expression of the lambda. ()部分是参数列表, =>表示右侧是 lambda 的主体/表达式。

Here's a slightly expanded form which may be a bit clearer这是一个稍微扩展的表格,可能会更清晰一些

Func<ItemType, string> linkFunction = (item) =>
{
  return Html.ActionLink("Edit", "Edit", new { id = item.Id });
};

That would be a lambda expression .那将是一个lambda 表达式 And no, using lambda's is not bad, it's a (very) good thing.不,使用 lambda 还不错,这是一件(非常)好事。

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

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