Static class/method this and generics
So I have a certain method I want to call on a List (it's a generic method that I run every time in different files, so I would like to put it in a static class).
The method is this:
public static List<Item> GetRangeOrMax(this List<Item> list, int amount)
{
return list.Count < amount ? list.GetRange(0, list.Count) : list.GetRange(0, amount);
}
The problem is that not every list I need to run this on is of the type Item. I was wondering if I would be 开发者_StackOverflow社区able to solve this using generics? Say something along the lines of (this List<T> list
...
The problem here being that the method must also return that value and I would like to keep using the this keyword. If not possible I guess I'll have to make the method with a different overloader for each type.
You can use a generic extension method.
static List<T> GetRangeOrMax<T>(this List<T> list, int amount)
{
return list.Count < amount ? list.GetRange(0, list.Count) : list.GetRange(0, amount);
}
精彩评论