开发者

Static class/method this and generics

开发者 https://www.devze.com 2023-03-29 01:15 出处:网络
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).

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);        
}
0

精彩评论

暂无评论...
验证码 换一张
取 消