Diciamo che ho scritto il mio metodo per invertire la lista.È possibile applicare un metodo generico a un elenco di elementi?
public static void MyReverse<T>(List<T> source)
{
var length = source.Count;
var hLength = length/2;
for (var i = 0; i < hLength; i++)
{
T temp = source[i];
source[i] = source[length - 1 - i];
source[length - 1 - i] = temp;
}
}
Lo chiamo così e funziona.
var fooList = new List<Foo>();
MyReverse(fooList);
Se voglio invertire più elenchi, lo chiamo così.
var fooList = new List<Foo>();
var barList = new List<Bar>();
var bazList = new List<Baz>();
MyReverse(fooList);
MyReverse(barList);
MyReverse(bazList);
Se voglio invertire un numero arbitrario di liste, mi piacerebbe provare:
public static void Main(string[] args)
{
var lists = new List<object>
{
new List<Foo>(),
new List<Bar>(),
new List<Bar>()
};
ReverseLists(lists);
}
public static void ReverseLists(List<object> sourceLists)
{
foreach (var sourceList in sourceLists)
{
MyReverse(sourceList); // Error: Type arguments cannot be inferred from usage
}
}
Ma questo genera un errore di compilazione. È ciò che sto cercando di fare possibile: potrebbe essere implementato il metodo ReverseLists
?
'sourceList' è' oggetto'. – leppie
@Rik: Chiaramente non renderà felice il compilatore ... – leppie
Se * veramente * ti serve, provalo con 'Elenco' come tipo di parametro di 'ReverseLists'. –
Ani