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);
}
为什么它不能编译?
编辑:错误是:
error CS0411:无法从使用中推断出方法“Namespace.Map<T,T2>(System.Collections.Generic.List<T>, System.Func<T,T2>)”的类型参数。尝试显式指定类型参数。
为什么我必须指定Map()函数的类型?它不能从传递的Func<T>
(在我的情况下是Square)中推断出吗?
答案是否与
C# 3.0泛型类型推断 - 将委托作为函数参数传递相同?