C#generics委托类型推断

为什么C#编译器不能在指定的示例中将T推断为int?

void Main() { int a = 0; Parse("1", x => a = x); // Compiler error: // Cannot convert expression type 'int' to return type 'T' } public void Parse(string x, Func setter) { var parsed = .... setter(parsed); } 

对lambda的方法类型推断要求在推断返回类型之前已知lambda参数的类型。 例如,如果你有:

 void M(A a, Func f1, Func f2) { } 

和一个电话

 M(1, a=>a.ToString(), b=>b.Length); 

然后我们推断:

 A is int, from the first argument Therefore the second parameter is Func. Therefore the second argument is (int a)=>a.ToString(); Therefore B is string. Therefore the third parameter is Func Therefore the third argument is (string b)=>b.Length Therefore C is int. And we're done. 

看,我们需要A来计算B,而B来计算C.在你的情况下,你想要从…中找出T。你不能那样做。

请参阅有关generics方法的http://msdn.microsoft.com/en-us/library/ms379564%28v=vs.80%29.aspx部分。

请注意,编译器无法仅根据返回值的类型推断类型。