为什么第一个和第三个表达式工作但不是第二个?Lambda表达式返回类型问题
var ss = new Func<int>(() => 0); //works
int x1 = new Func<int>(() => 0); //doesn't work --Cannot convert source type 'System.Func<int>' to target type 'int'
int x2 = new Func<string,int>((x) => 0)(""); //works
你基本上试图把'Func'放在一个类型为int的变量中;有一些错误;) –
Sehnsucht
'int x1 = new Func(()=> 0)();'会工作,因为您然后调用函数表达式,得到0结果,然后将其分配给int。尽管如此,这与返回值并没有多大关系,并且要注意,第一个作品是因为您可以将任何内容分配给var。第三个原因是因为您再次调用函数表达式(特别是使用字符串,因为它期望)。 –
@TravisJ我们不能把任何东西放在'var'; “只”的类型可以(静态地)从表达式中解析出来。例如'var foo = delegate(){return 0; };'不起作用 – Sehnsucht