c# - 将委托(delegate)分配给采用 N 个参数但未显式声明参数的函数

标签 c# delegates func

给定一个带有 N 个参数的函数,为什么可以为其分配一个未显式声明任何参数的委托(delegate)?例如

Func<int, string, object, string, bool> test;
// (1) this makes sense to me
test= delegate (int a, string b, object c, string d) { return true; };

// (2) this also makes sense to me
test= (a,b,c,d)=>true; 

// (3) why does this work? 
test = delegate { return true; }; 

为什么 (3) 有效? (1)、(2)、(3)之间有什么区别吗?我们可以从第三个变体的大括号内访问参数吗?

最佳答案

Why does (3) work?

来自C# programming guide on MSDN :

Anonymous methods enable you to omit the parameter list. This means that an anonymous method can be converted to delegates with a variety of signatures


Is there any difference between (1), (2), and (3)?

delegate keyword vs. lambda notation

Can we access the parameters from inside the braces of the third variation?

没有。如果您打算在匿名方法中使用参数,请不要省略参数列表。

关于c# - 将委托(delegate)分配给采用 N 个参数但未显式声明参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48812258/

相关文章:

c# - 您可以将 Func<EFContext, TResult> 包装在 Entities Context 中以供重用吗?

c# - 检查 bool 值是否为真?

c# - IE9 中没有设置 Cookie

c# - 关闭 ServiceStack 日志记录

ios - 了解委托(delegate)与 block 。 (重构代码以使用委托(delegate)而不是 block )

c# - 为什么我的 INT 变量是通过引用传递的? C#

使用函数 Func 作为参数的 C# 扩展

c# - 如何从 Azure DocumentDB 查询结果中选择第一个元素

c# - C# 中匿名 lambda 函数的 C++ 捕获子句等效项

c# - 在 C# 应用程序中使用 Func 类型