Powiedzmy, że napisałem własną metodę odwrócenia listy w miejscu.Czy istnieje możliwość zastosowania ogólnej metody do listy pozycji?
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;
}
}
Ja to tak nazywam i działa.
var fooList = new List<Foo>();
MyReverse(fooList);
Jeśli chcę cofnąć wiele list, nazywam to tak.
var fooList = new List<Foo>();
var barList = new List<Bar>();
var bazList = new List<Baz>();
MyReverse(fooList);
MyReverse(barList);
MyReverse(bazList);
Jeśli chcę, aby odwrócić dowolną liczbę list, będę próbować:
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
}
}
Ale to generuje błąd czasu kompilacji. Czy to, co próbuję zrobić, czy możliwe jest wdrożenie metody ReverseLists
?
'sourceList' jest' obiektem'. – leppie
@Rik: Najwyraźniej to nie sprawi, że kompilator będzie szczęśliwy ... – leppie
Jeśli * naprawdę * potrzebujesz tego, spróbuj z 'List' jako typ parametru 'ReverseLists'. –
Ani