2012-02-17 181 views
3

为什么C#编译器在指定的例子中推断T为int?C#泛型委托类型推断

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); 
} 
+0

你想做什么? – gdoron 2012-02-17 09:10:23

+1

我也无法推断。尝试'解析(...)' – 2012-02-17 09:12:25

+0

解析方法的语法糖。我可以用表情来做,但是我必须使用反思,这是不行的。 – m0sa 2012-02-17 09:13:10

回答

4

方法类型推断要求类型拉姆达参数的的类型返回被推断的前已知的。因此,举例来说,如果你有:

void M<A, B, C>(A a, Func<A, B> f1, Func<B, C> f2) { } 

和呼叫

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

那么我们就推断:

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. 

看到的,我们需要制定出B,和B工作out C.在你的情况下,你想从T得出T,而你不能这样做。

+0

当你把它放在那里时,它确实显得很明显... :) – m0sa 2012-02-18 09:16:37