C# lambda 使用花括号和不使用花括号时有什么区别? [重复]

问题描述 投票:0回答:2

C# lambda 使用花括号和不使用花括号时有什么区别?

我正在开发一个项目,我们有以下代码:

public void Configure(IApplicationBuilder app)
{
    ... //some other code goes here
    app.UseEndpoints(endpoint => endpoint.MapControllers());

    app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}

{ endpoints.MapControllers(); }
endpoint.MapControllers()
有什么区别吗?为什么
MapControllers
会被调用两次?

c# asp.net lambda middleware curly-braces
2个回答
2
投票

在第一种没有大括号的情况下,它将返回计算表达式的值

app.UseEndpoints(endpoint => endpoint.MapControllers());

在第二种情况下,有大括号的情况下,它允许您添加多个语句,最后您需要显式调用 return 语句来获取计算值。

app.UseEndpoints(endpoints => 
{ 
   other statements ...
   return endpoints.MapControllers(); 
});

2
投票

第一行

app.UseEndpoints(endpoint => endpoint.MapControllers());
没有大括号,这意味着它是一个单语句lambda表达式。它直接在端点参数上调用MapControllers方法。

在第二行

app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
中,花括号用于定义代码块。如果需要,它允许您包含多个语句。

至于为什么MapControllers会被调用两次,在这个上下文中似乎是多余的。这两行代码在功能上是等效的,并且实现了将控制器映射到端点的相同结果。

© www.soinside.com 2019 - 2024. All rights reserved.