Supponiamo che io sonoNET: i tipi generici dedotto sui metodi statici
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);
}
Perché non compilare?
EDIT: L'errore è:
errore CS0411: Gli argomenti di tipo per il metodo 'Namespace.Map < T, T2 > (System.Collections.Generic.List <T>, System.Func < T, T2 >) "non può essere dedotto dall'utilizzo. Prova a specificare esplicitamente gli argomenti del tipo.
Perché devo specificare il tipo di funzione Map()? Non può dedurre questo dal passato Func<T>
? (Nel mio caso, Piazza)
Se la soluzione lo stesso che per
C# 3.0 generic type inference - passing a delegate as a function parameter?
Interessante. Ti dispiacerebbe postare l'errore del compilatore? –
Qual è il risultato se si modifica la var nella prima riga di Run() su List? –
@tehMick: il risultato sarà lo stesso. Il tipo è dedotto. –