2012-02-17 180 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