假設我有.NET:推斷通用類型的靜態方法
public static List<T2> Map<T,T2>(List<T> inputs, Func<T, T2> f)
{
return inputs.ConvertAll((x) => f(x));
}
private int Square(int x) { return x*x; }
public void Run()
{
var inputs = new List<Int32>(new int[]{2,4,8,16,32,64,128,256,512,1024,2048});
// this does not compile
var outputs = Map(inputs, Square);
// this is fine
var outputs2 = Map<Int32,Int32>(inputs, Square);
// this is also fine (thanks, Jason)
var outputs2 = Map<Int32,Int32>(inputs, (x)=>x*x);
// also fine
var outputs2 = Map(inputs, (x)=>x*x);
}
爲什麼它不能編譯?
EDIT:錯誤是:
錯誤CS0411:用於方法的類型參數「Namespace.Map < T,T2 >(System.Collections.Generic.List <Ť>,System.Func < T,T2 >)'不能從使用中推斷出來。嘗試明確指定類型參數。
爲什麼我必須指定Map()函數的類型?難道它不能通過傳遞Func<T>
推斷這一點嗎? (在我的情況,廣場)
答案是一樣的
C# 3.0 generic type inference - passing a delegate as a function parameter?
有趣。你介意發佈編譯器錯誤嗎? – 2010-01-21 04:26:04
如果將Run()的第一行中的var更改爲List,結果如何? –
2010-01-21 04:38:01
@tehMick:結果將是相同的。推斷類型。 – 2010-01-21 04:42:14