Joe*_*Joe 12 c# anonymous-function
我试图弄清楚C#的匿名函数的语法,对我来说没有意义.为什么这是有效的
Func<string, string> f = x => { return "Hello, world!"; };
Run Code Online (Sandbox Code Playgroud)
但这不是?
Func<string> g = { return "Hello, world!"; };
Run Code Online (Sandbox Code Playgroud)
Ree*_*sey 29
第二个仍然需要lambda语法:
Func<string> g = () => { return "Hello, world!"; };
Run Code Online (Sandbox Code Playgroud)
首先,你有效地写作:
Func<string, string> f = (x) => { return "Hello, world!"; };
Run Code Online (Sandbox Code Playgroud)
但是()如果只有一个参数,C#会让你在定义一个lambda时放弃,让你改写x =>.如果没有参数,则必须包含().
这在C#语言规范的第7.15节中规定:
在具有单个隐式类型参数的匿名函数中,可以从参数列表中省略括号.换句话说,表单的匿名函数
(param)=> expr
可以缩写为
param => expr