C# 泛型委托类型推断

m0s*_*0sa 3 c# generics delegates

为什么 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<T>(string x, Func<T, T> setter)
{
    var parsed = ....
    setter(parsed);
}
Run Code Online (Sandbox Code Playgroud)

Eri*_*ert 5

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

void M<A, B, C>(A a, Func<A, B> f1, Func<B, C> f2) { }
Run Code Online (Sandbox Code Playgroud)

和一个电话

M(1, a=>a.ToString(), b=>b.Length);
Run Code Online (Sandbox Code Playgroud)

那么我们可以推断:

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

看,我们需要 A 来算出 B,需要 B 来算出 C。在您的情况下,您想从... T 算出 T。但您不能这样做。